<?php
require_once __DIR__ . '/../MPHX/common.php';

if (!is_admin_login()) {
    header('Location: /admin/login.php');
    exit;
}

$gn = isset($_GET['gn']) ? $_GET['gn'] : '';
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>列表管理 - 宝塔主机管理系统</title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/css/all.min.css">
    <link rel="stylesheet" href="css/style.css?v=2026040501">
    <script src="/static/js/jquery.min.js"></script>
    <script src="/static/js/bootstrap.min.js"></script>
    <style>
        /* 宝塔列表移动端适配 - 保持PC布局，支持横向滑动 */
        @media (max-width: 768px) {
            .table-responsive {
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
            }
            #bt-table {
                min-width: 800px;
            }
            #bt-table th,
            #bt-table td {
                white-space: nowrap;
                font-size: 12px;
            }
            #bt-table td.bt-actions {
                padding: 8px;
                white-space: nowrap !important;
            }
            #bt-table td.bt-actions .btn {
                display: inline-block !important;
                width: auto !important;
                height: auto !important;
                min-width: auto !important;
                min-height: auto !important;
                margin: 0 2px !important;
                padding: 4px 8px !important;
                font-size: 11px !important;
                line-height: 1.2;
                white-space: nowrap;
                border-radius: 4px;
            }
            #bt-table td.bt-actions .btn i {
                font-size: 10px;
                margin-right: 3px;
            }
            #bt-table td.bt-actions .btn .btn-text {
                display: inline !important;
            }
            /* 程序列表工具栏移动端适配 - 统一按钮大小 */
            .content-area .card .table-toolbar .toolbar-left {
                display: flex !important;
                flex-wrap: wrap !important;
                gap: 6px !important;
                align-items: center !important;
            }
            /* 所有按钮统一大小 - 覆盖style.css的100%宽度 */
            .content-area .card .table-toolbar .toolbar-left .btn.btn-sm,
            .content-area .card .table-toolbar .toolbar-left .d-inline-block .btn.btn-sm {
                padding: 4px 10px !important;
                font-size: 11px !important;
                height: 30px !important;
                line-height: 1.3 !important;
                white-space: nowrap !important;
                margin: 0 !important;
                flex: 0 0 auto !important;
                width: auto !important;
                min-height: 30px !important;
                display: inline-flex !important;
                align-items: center !important;
                justify-content: center !important;
                border-radius: 4px !important;
            }
            .content-area .card .table-toolbar .toolbar-left .btn i {
                font-size: 10px !important;
                margin-right: 3px !important;
            }
            /* 分类选择区域 */
            .content-area .card .table-toolbar .toolbar-left .d-inline-block {
                display: inline-flex !important;
                gap: 6px !important;
                margin: 0 !important;
                width: auto !important;
                align-items: center !important;
            }
            .content-area .card .table-toolbar .toolbar-left .d-inline-block select {
                width: auto !important;
                padding: 4px 8px !important;
                font-size: 11px !important;
                height: 30px !important;
                min-height: 30px !important;
            }
            /* 强制更新分类按钮不扩展 */
            .content-area .card .table-toolbar .toolbar-left .d-inline-block #cx-batch-update-category {
                width: auto !important;
                flex: 0 0 auto !important;
                min-width: auto !important;
            }
        }
    </style>
</head>
<body>
    <div class="content-area">
        <?php if ($gn == 'bt'): ?>
        <div class="card">
            <h3><i class="fas fa-network-wired"></i> 宝塔列表</h3>
            <div class="table-toolbar">
                <div class="toolbar-left">
                    <a href="add.php?gn=bt" class="btn btn-primary btn-sm"><i class="fas fa-plus"></i> 添加宝塔</a>
                    <button class="btn btn-danger btn-sm" id="bt-batch-delete"><i class="fas fa-trash-alt"></i> 删除选中</button>
                    <button class="btn btn-secondary btn-sm" id="bt-export"><i class="fas fa-file-export"></i> 导出CSV</button>
                    <button class="btn btn-info btn-sm" id="bt-refresh"><i class="fas fa-sync"></i> 刷新</button>
                </div>
                <div class="toolbar-right">
                    <input type="text" id="bt-keyword" class="form-control form-control-sm" placeholder="搜索关键词" style="width: 150px; display: inline-block;">
                    <select id="bt-status" class="form-control form-control-sm" style="width: 100px; display: inline-block;">
                        <option value="">全部状态</option>
                        <option value="true">开启</option>
                        <option value="false">关闭</option>
                    </select>
                    <select id="bt-os" class="form-control form-control-sm" style="width: 100px; display: inline-block;">
                        <option value="">全部系统</option>
                        <option value="Linux">Linux</option>
                        <option value="Windows">Windows</option>
                    </select>
                    <button class="btn btn-primary btn-sm" id="bt-search"><i class="fas fa-search"></i> 搜索</button>
                    <button class="btn btn-secondary btn-sm" id="bt-reset"><i class="fas fa-undo"></i> 重置</button>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table" id="bt-table">
                    <thead>
                        <tr>
                            <th style="width: 40px;"><input type="checkbox" id="bt-check-all"></th>
                            <th>ID</th>
                            <th>宝塔名字</th>
                            <th>IP地址</th>
                            <th>端口</th>
                            <th>编号</th>
                            <th>操作系统</th>
                            <th>状态</th>
                            <th>连通</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="bt-body">
                        <tr><td colspan="10" class="text-center text-muted">加载中...</td></tr>
                    </tbody>
                </table>
            </div>
            <div class="pagination" id="bt-pagination"></div>
        </div>
        
        <!-- 编辑宝塔服务器模态框 -->
        <div class="modal fade" id="editBtModal" tabindex="-1" role="dialog" aria-labelledby="editBtModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="editBtModalLabel">编辑宝塔服务器</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form id="editBtForm">
                            <input type="hidden" id="editBtId" name="id">
                            <div class="form-group">
                                <label for="editBtMc">宝塔名字 <span style="color: red;">*</span></label>
                                <input type="text" class="form-control" id="editBtMc" name="btmc" required>
                            </div>
                            <div class="form-group">
                                <label for="editBtIp">IP地址 <span style="color: red;">*</span></label>
                                <input type="text" class="form-control" id="editBtIp" name="ip" required>
                            </div>
                            <div class="form-group">
                                <label for="editBtPort">端口 <span style="color: red;">*</span></label>
                                <input type="text" class="form-control" id="editBtPort" name="port" required>
                            </div>
                            <div class="form-group">
                                <label for="editBtKey">API密钥 <span style="color: red;">*</span></label>
                                <input type="text" class="form-control" id="editBtKey" name="key" required>
                            </div>
                            <div class="form-group">
                                <label for="editBtFtp">FTP地址</label>
                                <input type="text" class="form-control" id="editBtFtp" name="ftp">
                            </div>
                            <div class="form-group">
                                <label for="editBtBzbh">宝塔编号 <span style="color: red;">*</span></label>
                                <input type="text" class="form-control" id="editBtBzbh" name="bzbh" required>
                            </div>
                            <div class="form-group">
                                <label for="editBtStatus">状态</label>
                                <select class="form-control" id="editBtStatus" name="status">
                                    <option value="true">开启</option>
                                    <option value="false">关闭</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="editBtOs">操作系统</label>
                                <select class="form-control" id="editBtOs" name="os" required>
                                    <option value="Linux">Linux</option>
                                    <option value="Windows">Windows</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <div class="custom-control custom-checkbox">
                                    <input type="checkbox" class="custom-control-input" id="editBtAqfw" name="aqfw">
                                    <label class="custom-control-label" for="editBtAqfw">安全访问 (HTTPS)</label>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                        <button type="button" class="btn btn-primary" onclick="saveEditBt()">保存</button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 对接教程选择模态框 -->
        <div class="modal fade" id="tutorialModal" tabindex="-1" role="dialog" aria-labelledby="tutorialModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="tutorialModalLabel">选择对接系统</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body py-3">
                        <input type="hidden" id="tutorialBtId" value="">
                        <p class="text-center mb-3 text-muted" style="font-size: 13px;">请选择对接系统</p>
                        <div class="d-flex justify-content-center gap-2 flex-wrap">
                            <button type="button" class="btn btn-primary" style="min-width: 120px;" onclick="viewSwTutorial()">
                                <i class="fas fa-exchange-alt mr-1"></i>SWAPIDC
                            </button>
                            <button type="button" class="btn btn-success" style="min-width: 120px;" onclick="viewMfTutorial()">
                                <i class="fas fa-cube mr-1"></i>魔方财务
                            </button>
                            <button type="button" class="btn btn-info" style="min-width: 120px; display: none;" onclick="viewMv10Tutorial()">
                                <i class="fas fa-server mr-1"></i>魔方V10
                            </button>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>
        
        <script>
        var btState = {page: 1, limit: 10, total: 0};

        function escapeHtml(text) {
            if (text === null || text === undefined) return '';
            return String(text).replace(/[&<>\"]/g, function(match) {
                return {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;'}[match];
            });
        }

        function renderBtRows(rows) {
            if (!rows || rows.length === 0) {
                $('#bt-body').html('<tr><td colspan="10" class="text-center text-muted">暂无宝塔记录</td></tr>');
                return;
            }
            var html = '';
            rows.forEach(function(row) {
                var statusBadge = row.jkkg === 'true' ? '<span class="badge badge-success">开启</span>' : '<span class="badge badge-danger">关闭</span>';
                html += '<tr>' +
                    '<td><input type="checkbox" class="bt-check" value="' + escapeHtml(row.id) + '"></td>' +
                    '<td>' + escapeHtml(row.id) + '</td>' +
                    '<td>' + escapeHtml(row.btmc || '-') + '</td>' +
                    '<td>' + escapeHtml(row.ip || '-') + '</td>' +
                    '<td>' + escapeHtml(row.dk || '-') + '</td>' +
                    '<td>' + escapeHtml(row.bzbh || '-') + '</td>' +
                    '<td>' + escapeHtml(row.czzt || '-') + '</td>' +
                    '<td>' + statusBadge + '</td>' +
                    '<td><span class="badge badge-info" id="lt-' + escapeHtml(row.id) + '">待检测</span></td>' +
                    '<td class="bt-actions">' +
                    '<button class="btn btn-info btn-sm bt-tutorial" data-id="' + escapeHtml(row.id) + '" title="对接教程"><i class="fas fa-book"></i><span class="btn-text"> 对接教程</span></button> ' +
                    '<button class="btn btn-primary btn-sm bt-check" data-id="' + escapeHtml(row.id) + '" data-ip="' + escapeHtml(row.ip) + '" data-port="' + escapeHtml(row.dk) + '" data-key="' + escapeHtml(row.key) + '" data-aqfw="' + escapeHtml(row.aqfw) + '" title="检查"><i class="fas fa-plug"></i><span class="btn-text"> 检查</span></button> ' +
                    '<button class="btn btn-warning btn-sm bt-edit" data-id="' + escapeHtml(row.id) + '" data-btmc="' + escapeHtml(row.btmc) + '" data-ip="' + escapeHtml(row.ip) + '" data-port="' + escapeHtml(row.dk) + '" data-key="' + escapeHtml(row.key) + '" data-ftp="' + escapeHtml(row.ftp) + '" data-bzbh="' + escapeHtml(row.bzbh) + '" data-status="' + escapeHtml(row.jkkg) + '" data-os="' + escapeHtml(row.czzt) + '" data-aqfw="' + escapeHtml(row.aqfw) + '" title="编辑"><i class="fas fa-edit"></i><span class="btn-text"> 编辑</span></button> ' +
                    '<button class="btn btn-danger btn-sm bt-delete" data-id="' + escapeHtml(row.id) + '" title="删除"><i class="fas fa-trash-alt"></i><span class="btn-text"> 删除</span></button>' +
                    '</td>' +
                    '</tr>';
            });
            $('#bt-body').html(html);
        }

        function renderPagination(containerId, state, onPage) {
            var totalPages = Math.max(1, Math.ceil(state.total / state.limit));
            var current = state.page;
            var html = '';
            var start = Math.max(1, current - 2);
            var end = Math.min(totalPages, current + 2);

            html += '<button class="page-btn" ' + (current === 1 ? 'disabled' : '') + ' data-page="' + (current - 1) + '">上一页</button>';
            for (var i = start; i <= end; i++) {
                html += '<button class="page-btn ' + (i === current ? 'active' : '') + '" data-page="' + i + '">' + i + '</button>';
            }
            html += '<button class="page-btn" ' + (current === totalPages ? 'disabled' : '') + ' data-page="' + (current + 1) + '">下一页</button>';
            $('#' + containerId).html(html);
            $('#' + containerId + ' .page-btn').off('click').on('click', function() {
                var page = parseInt($(this).data('page'), 10);
                if (!isNaN(page) && page >= 1 && page <= totalPages && page !== current) {
                    onPage(page);
                }
            });
        }

        function loadBtList(page) {
            btState.page = page || btState.page;
            $('#bt-body').html('<tr><td colspan="10" class="text-center text-muted">加载中...</td></tr>');

            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {
                    egn: 'listbt',
                    page: btState.page,
                    limit: btState.limit,
                    keyword: $('#bt-keyword').val(),
                    status: $('#bt-status').val(),
                    os: $('#bt-os').val()
                },
                dataType: 'json',
                success: function(data) {
                    btState.total = data.total || 0;
                    renderBtRows(data.rows || []);
                    renderPagination('bt-pagination', btState, loadBtList);
                    // 页面加载完成后自动检查连通性
                    setTimeout(function() {
                        autoCheckBtConn(data.rows || []);
                    }, 500);
                },
                error: function() {
                    $('#bt-body').html('<tr><td colspan="10" class="text-center text-muted">加载失败，请重试</td></tr>');
                }
            });
        }
        
        // 自动检查宝塔连通性
        function autoCheckBtConn(rows) {
            if (!rows || rows.length === 0) return;
            
            rows.forEach(function(row, index) {
                // 延迟检查，避免同时发送太多请求
                setTimeout(function() {
                    var $lt = $('#lt-' + row.id);
                    if ($lt.length === 0) return;
                    
                    $lt.html('检查中...').removeClass('badge-success badge-danger').addClass('badge-info');
                    
                    $.ajax({
                        type: 'POST',
                        url: 'ajax.php',
                        data: {
                            egn: 'check_conn',
                            ip: row.ip,
                            port: row.dk,
                            key: row.key,
                            aqfw: row.aqfw
                        },
                        dataType: 'json',
                        xhrFields: {
                            withCredentials: true
                        },
                        success: function(data) {
                            if(data.code == 'success') {
                                $lt.html('连通').removeClass('badge-info badge-danger').addClass('badge-success');
                            } else {
                                $lt.html('失败').removeClass('badge-info badge-success').addClass('badge-danger');
                            }
                        },
                        error: function() {
                            $lt.html('错误').removeClass('badge-info badge-success').addClass('badge-danger');
                        }
                    });
                }, index * 300); // 每个宝塔延迟300ms检查，避免并发过多
            });
        }

        function saveEditBt() {
            var id = $('#editBtId').val();
            var btmc = $('#editBtMc').val();
            var ip = $('#editBtIp').val();
            var port = $('#editBtPort').val();
            var key = $('#editBtKey').val();
            var ftp = $('#editBtFtp').val();
            var bzbh = $('#editBtBzbh').val();
            var status = $('#editBtStatus').val();
            var os = $('#editBtOs').val();
            var aqfw = $('#editBtAqfw').is(':checked') ? 'true' : 'false';
            
            if (!btmc || !ip || !port || !key || !bzbh || !os) {
                alert('请填写所有必填字段');
                return;
            }
            
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {egn: 'edit_bt', id: id, btmc: btmc, ip: ip, port: port, key: key, ftp: ftp, bzbh: bzbh, status: status, os: os, aqfw: aqfw},
                dataType: 'json',
                success: function(data) {
                    alert(data.code);
                    if(data.code == '编辑成功') {
                        $('#editBtModal').modal('hide');
                        loadBtList(btState.page);
                    }
                },
                error: function() {
                    alert('操作失败，请重试');
                }
            });
        }
        
        function checkConn(id, ip, port, key, aqfw, btn) {
            var $btn = $(btn);
            var originalText = $btn.html();
            var $lt = $('#lt-' + id);
            
            $btn.addClass('btn-loading').prop('disabled', true);
            $lt.html('检查中...').removeClass('badge-success badge-danger').addClass('badge-info');
            
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {egn: 'check_conn', ip: ip, port: port, key: key, aqfw: aqfw},
                dataType: 'json',
                xhrFields: {
                    withCredentials: true
                },
                success: function(data) {
                    $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                    if(data.code == 'success') {
                        $lt.html('连通').removeClass('badge-info badge-danger').addClass('badge-success');
                    } else {
                        $lt.html('失败').removeClass('badge-info badge-success').addClass('badge-danger');
                    }
                },
                error: function() {
                    $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                    $lt.html('错误').removeClass('badge-info badge-success').addClass('badge-danger');
                }
            });
        }
        
        function editbt(id, btmc, ip, port, key, ftp, bzbh, status, os, aqfw, btn) {
            $('#editBtId').val(id);
            $('#editBtMc').val(btmc || '');
            $('#editBtIp').val(ip || '');
            $('#editBtPort').val(port || '');
            $('#editBtKey').val(key || '');
            $('#editBtFtp').val(ftp || '');
            $('#editBtBzbh').val(bzbh || '');
            $('#editBtStatus').val(status || 'true');
            $('#editBtOs').val(os || 'Linux');
            $('#editBtAqfw').prop('checked', aqfw === 'true');
            $('#editBtModal').modal('show');
        }

        function delbt(id) {
            if(confirm('确定要删除这个宝塔服务器吗？')) {
                $.ajax({
                    type: 'POST',
                    url: 'ajax.php',
                    data: {egn: 'btsc', id: id},
                    dataType: 'json',
                    success: function(data) {
                        alert(data.code);
                        if(data.code == '删除成功') {
                            loadBtList(1);
                        }
                    },
                    error: function() {
                        alert('操作失败，请重试');
                    }
                });
            }
        }

        function batchDeleteBt(ids) {
            if (!ids || ids.length === 0) {
                alert('请选择要删除的宝塔');
                return;
            }
            if (!confirm('确定要删除选中的宝塔服务器吗？')) return;
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {egn: 'btscxz', idsz: ids},
                dataType: 'json',
                success: function(data) {
                    alert(data.code || '操作完成');
                    loadBtList(1);
                },
                error: function() {
                    alert('操作失败，请重试');
                }
            });
        }

        function exportBt(ids) {
            var form = $('<form>', {method: 'post', action: 'ajax.php', target: '_blank'});
            form.append($('<input>', {type: 'hidden', name: 'egn', value: 'exportbt'}));
            form.append($('<input>', {type: 'hidden', name: 'keyword', value: $('#bt-keyword').val()}));
            form.append($('<input>', {type: 'hidden', name: 'status', value: $('#bt-status').val()}));
            form.append($('<input>', {type: 'hidden', name: 'os', value: $('#bt-os').val()}));
            if (ids && ids.length > 0) {
                form.append($('<input>', {type: 'hidden', name: 'ids', value: ids.join(',')}));
            }
            $('body').append(form);
            form.submit();
            form.remove();
        }
        
        // 对接教程模态框
        function viewTutorial(id) {
            $('#tutorialBtId').val(id);
            $('#tutorialModal').modal('show');
        }
        
        function viewSwTutorial() {
            var id = $('#tutorialBtId').val();
            $('#tutorialModal').modal('hide');
            window.open('tutorial.php?gn=sw&sz=' + id, '_blank');
        }
        
        function viewMfTutorial() {
            var id = $('#tutorialBtId').val();
            $('#tutorialModal').modal('hide');
            window.open('tutorial.php?gn=mr&sz=' + id, '_blank');
        }
        
        function viewMv10Tutorial() {
            var id = $('#tutorialBtId').val();
            $('#tutorialModal').modal('hide');
            window.open('tutorial.php?gn=mv10&sz=' + id, '_blank');
        }

        $(document).ready(function() {
            loadBtList(1);

            $('#bt-search').on('click', function() { loadBtList(1); });
            $('#bt-reset').on('click', function() {
                $('#bt-keyword').val('');
                $('#bt-status').val('');
                $('#bt-os').val('');
                loadBtList(1);
            });
            $('#bt-refresh').on('click', function() { loadBtList(btState.page); });
            $('#bt-export').on('click', function() {
                var ids = $('.bt-check:checked').map(function() { return $(this).val(); }).get();
                exportBt(ids);
            });
            $('#bt-batch-delete').on('click', function() {
                var ids = $('.bt-check:checked').map(function() { return $(this).val(); }).get();
                batchDeleteBt(ids);
            });
            $('#bt-check-all').on('change', function() {
                $('.bt-check').prop('checked', $(this).is(':checked'));
            });
            $('#bt-table').on('click', '.bt-delete', function() {
                delbt($(this).data('id'));
            });
            $('#bt-table').on('click', '.bt-check', function() {
                checkConn($(this).data('id'), $(this).data('ip'), $(this).data('port'), $(this).data('key'), $(this).data('aqfw'), this);
            });
            $('#bt-table').on('click', '.bt-edit', function() {
                editbt($(this).data('id'), $(this).data('btmc'), $(this).data('ip'), $(this).data('port'), $(this).data('key'), $(this).data('ftp'), $(this).data('bzbh'), $(this).data('status'), $(this).data('os'), $(this).data('aqfw'), this);
            });
            $('#bt-table').on('click', '.bt-tutorial', function() {
                viewTutorial($(this).data('id'));
            });
        });
        </script>
        
        <?php elseif ($gn == 'ym'): ?>
        <div class="card">
            <h3><i class="fas fa-globe"></i> 域名列表</h3>
            <div class="table-toolbar">
                <div class="toolbar-left">
                    <a href="add.php?gn=ym" class="btn btn-primary btn-sm"><i class="fas fa-plus"></i> 添加域名</a>
                    <button class="btn btn-danger btn-sm" id="ym-batch-delete"><i class="fas fa-trash-alt"></i> 删除选中</button>
                    <button class="btn btn-secondary btn-sm" id="ym-export"><i class="fas fa-file-export"></i> 导出CSV</button>
                    <button class="btn btn-info btn-sm" id="ym-refresh"><i class="fas fa-sync"></i> 刷新</button>
                </div>
                <div class="toolbar-right">
                    <input type="text" class="form-control form-control-sm" id="ym-keyword" placeholder="域名/简介">
                    <button class="btn btn-primary btn-sm" id="ym-search"><i class="fas fa-search"></i> 查询</button>
                    <button class="btn btn-light btn-sm" id="ym-reset"><i class="fas fa-redo"></i> 重置</button>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table" id="ym-table">
                    <thead>
                        <tr>
                            <th style="width: 40px;"><input type="checkbox" id="ym-check-all"></th>
                            <th>ID</th>
                            <th>域名</th>
                            <th>价格</th>
                            <th>简介</th>
                            <th>所属宝塔</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="ym-body">
                        <tr><td colspan="7" class="text-center text-muted">加载中...</td></tr>
                    </tbody>
                </table>
            </div>
            <div class="pagination" id="ym-pagination"></div>
        </div>

        <!-- 编辑域名模态框 -->
        <div class="modal fade" id="editYmModal" tabindex="-1" role="dialog" aria-labelledby="editYmModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="editYmModalLabel">编辑域名</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form id="editYmForm">
                            <input type="hidden" id="editYmId" name="id">
                            <div class="form-group">
                                <label for="editYmName">域名 <span style="color: red;">*</span></label>
                                <input type="text" class="form-control" id="editYmName" name="ym" required>
                            </div>
                            <div class="form-group">
                                <label for="editYmPrice">价格 <span style="color: red;">*</span></label>
                                <input type="text" class="form-control" id="editYmPrice" name="jg" required>
                            </div>
                            <div class="form-group">
                                <label for="editYmDesc">简介</label>
                                <textarea class="form-control" id="editYmDesc" name="js"></textarea>
                            </div>
                            <div class="form-group">
                                <label for="editYmBt">所属宝塔</label>
                                <select class="form-control" id="editYmBt" name="btid">
                                    <?php
                                    $bts = $DB->query("SELECT * FROM `bt` ORDER BY `id` DESC");
                                    while ($bt = $DB->fetch($bts)) {
                                        echo '<option value="' . $bt['id'] . '">' . $bt['ip'] . '</option>';
                                    }
                                    ?>
                                </select>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                        <button type="button" class="btn btn-primary" onclick="saveEditYm()">保存</button>
                    </div>
                </div>
            </div>
        </div>
        
        <script>
        var ymState = {page: 1, limit: 10, total: 0};

        function escapeYmHtml(text) {
            if (text === null || text === undefined) return '';
            return String(text).replace(/[&<>\"]/g, function(match) {
                return {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;'}[match];
            });
        }

        function renderYmRows(rows) {
            if (!rows || rows.length === 0) {
                $('#ym-body').html('<tr><td colspan="7" class="text-center text-muted">暂无域名记录</td></tr>');
                return;
            }
            var html = '';
            rows.forEach(function(row) {
                html += '<tr>' +
                    '<td><input type="checkbox" class="ym-check" value="' + escapeYmHtml(row.id) + '"></td>' +
                    '<td>' + escapeYmHtml(row.id) + '</td>' +
                    '<td>' + escapeYmHtml(row.ym || '-') + '</td>' +
                    '<td>' + escapeYmHtml(row.jg || '-') + '</td>' +
                    '<td>' + escapeYmHtml(row.js || '-') + '</td>' +
                    '<td>' + escapeYmHtml(row.bt_ip || '-') + '</td>' +
                    '<td>' +
                    '<button class="btn btn-warning btn-sm ym-edit" data-id="' + escapeYmHtml(row.id) + '" data-ym="' + escapeYmHtml(row.ym) + '" data-jg="' + escapeYmHtml(row.jg) + '" data-js="' + escapeYmHtml(row.js) + '" data-btid="' + escapeYmHtml(row.btid) + '"><i class="fas fa-edit"></i> 编辑</button> ' +
                    '<button class="btn btn-danger btn-sm ym-delete" data-id="' + escapeYmHtml(row.id) + '"><i class="fas fa-trash-alt"></i> 删除</button>' +
                    '</td>' +
                    '</tr>';
            });
            $('#ym-body').html(html);
        }

        function renderYmPagination(containerId, state, onPage) {
            var totalPages = Math.max(1, Math.ceil(state.total / state.limit));
            var current = state.page;
            var html = '';
            var start = Math.max(1, current - 2);
            var end = Math.min(totalPages, current + 2);

            html += '<button class="page-btn" ' + (current === 1 ? 'disabled' : '') + ' data-page="' + (current - 1) + '">上一页</button>';
            for (var i = start; i <= end; i++) {
                html += '<button class="page-btn ' + (i === current ? 'active' : '') + '" data-page="' + i + '">' + i + '</button>';
            }
            html += '<button class="page-btn" ' + (current === totalPages ? 'disabled' : '') + ' data-page="' + (current + 1) + '">下一页</button>';
            $('#' + containerId).html(html);
            $('#' + containerId + ' .page-btn').off('click').on('click', function() {
                var page = parseInt($(this).data('page'), 10);
                if (!isNaN(page) && page >= 1 && page <= totalPages && page !== current) {
                    onPage(page);
                }
            });
        }

        function loadYmList(page) {
            ymState.page = page || ymState.page;
            $('#ym-body').html('<tr><td colspan="7" class="text-center text-muted">加载中...</td></tr>');

            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {
                    egn: 'listym',
                    page: ymState.page,
                    limit: ymState.limit,
                    keyword: $('#ym-keyword').val()
                },
                dataType: 'json',
                success: function(data) {
                    ymState.total = data.total || 0;
                    renderYmRows(data.rows || []);
                    renderYmPagination('ym-pagination', ymState, loadYmList);
                },
                error: function() {
                    $('#ym-body').html('<tr><td colspan="7" class="text-center text-muted">加载失败，请重试</td></tr>');
                }
            });
        }

        function saveEditYm() {
            var id = $('#editYmId').val();
            var ym = $('#editYmName').val();
            var jg = $('#editYmPrice').val();
            var js = $('#editYmDesc').val();
            var btid = $('#editYmBt').val();

            if (!ym || !jg) {
                alert('请填写域名和价格');
                return;
            }

            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {egn: 'edit_ym', id: id, ym: ym, jg: jg, js: js, btid: btid},
                dataType: 'json',
                success: function(data) {
                    alert(data.code);
                    if(data.code == '编辑成功') {
                        $('#editYmModal').modal('hide');
                        loadYmList(ymState.page);
                    }
                },
                error: function() {
                    alert('操作失败，请重试');
                }
            });
        }

        function delym(id) {
            if(confirm('确定要删除这个域名吗？')) {
                $.ajax({
                    type: 'POST',
                    url: 'ajax.php',
                    data: {egn: 'ymsc', id: id},
                    dataType: 'json',
                    success: function(data) {
                        alert(data.code);
                        if(data.code == '删除成功') {
                            loadYmList(1);
                        }
                    },
                    error: function() {
                        alert('操作失败，请重试');
                    }
                });
            }
        }

        function batchDeleteYm(ids) {
            if (!ids || ids.length === 0) {
                alert('请选择要删除的域名');
                return;
            }
            if (!confirm('确定要删除选中的域名吗？')) return;
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {egn: 'ymscxz', idsz: ids},
                dataType: 'json',
                success: function(data) {
                    alert(data.code || '操作完成');
                    loadYmList(1);
                },
                error: function() {
                    alert('操作失败，请重试');
                }
            });
        }

        function exportYm(ids) {
            var form = $('<form>', {method: 'post', action: 'ajax.php', target: '_blank'});
            form.append($('<input>', {type: 'hidden', name: 'egn', value: 'exportym'}));
            form.append($('<input>', {type: 'hidden', name: 'keyword', value: $('#ym-keyword').val()}));
            if (ids && ids.length > 0) {
                form.append($('<input>', {type: 'hidden', name: 'ids', value: ids.join(',')}));
            }
            $('body').append(form);
            form.submit();
            form.remove();
        }

        $(document).ready(function() {
            loadYmList(1);

            $('#ym-search').on('click', function() { loadYmList(1); });
            $('#ym-reset').on('click', function() {
                $('#ym-keyword').val('');
                loadYmList(1);
            });
            $('#ym-refresh').on('click', function() { loadYmList(ymState.page); });
            $('#ym-export').on('click', function() {
                var ids = $('.ym-check:checked').map(function() { return $(this).val(); }).get();
                exportYm(ids);
            });
            $('#ym-batch-delete').on('click', function() {
                var ids = $('.ym-check:checked').map(function() { return $(this).val(); }).get();
                batchDeleteYm(ids);
            });
            $('#ym-check-all').on('change', function() {
                $('.ym-check').prop('checked', $(this).is(':checked'));
            });
            $('#ym-table').on('click', '.ym-delete', function() {
                delym($(this).data('id'));
            });
            $('#ym-table').on('click', '.ym-edit', function() {
                $('#editYmId').val($(this).data('id'));
                $('#editYmName').val($(this).data('ym'));
                $('#editYmPrice').val($(this).data('jg'));
                $('#editYmDesc').val($(this).data('js'));
                $('#editYmBt').val($(this).data('btid'));
                $('#editYmModal').modal('show');
            });
        });
        </script>
        
        <?php elseif ($gn == 'zj'): ?>
        <div class="card">
            <h3><i class="fas fa-laptop"></i> 主机列表</h3>
            <div class="table-toolbar">
                <div class="toolbar-left">
                    <a href="add.php?gn=zj" class="btn btn-primary btn-sm"><i class="fas fa-plus"></i> 添加主机</a>
                    <button class="btn btn-danger btn-sm" id="zj-batch-delete"><i class="fas fa-trash-alt"></i> 删除选中</button>
                    <button class="btn btn-secondary btn-sm" id="zj-export"><i class="fas fa-file-export"></i> 导出CSV</button>
                    <button class="btn btn-info btn-sm" id="zj-refresh"><i class="fas fa-sync"></i> 刷新</button>
                </div>
                <div class="toolbar-right">
                    <input type="text" class="form-control form-control-sm" id="zj-keyword" placeholder="用户名/类型">
                    <button class="btn btn-primary btn-sm" id="zj-search"><i class="fas fa-search"></i> 查询</button>
                    <button class="btn btn-light btn-sm" id="zj-reset"><i class="fas fa-redo"></i> 重置</button>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table" id="zj-table">
                    <thead>
                        <tr>
                            <th style="width: 40px;"><input type="checkbox" id="zj-check-all"></th>
                            <th>ID</th>
                            <th>用户名</th>
                            <th>类型</th>
                            <th>网页空间</th>
                            <th>数据库空间</th>
                            <th>流量</th>
                            <th>到期时间</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="zj-body">
                        <tr><td colspan="10" class="text-center text-muted">加载中...</td></tr>
                    </tbody>
                </table>
            </div>
            <div class="pagination" id="zj-pagination"></div>
        </div>
        
        <!-- 编辑主机模态框 -->
        <div class="modal fade" id="editZjModal" tabindex="-1" role="dialog" aria-labelledby="editZjModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="editZjModalLabel">编辑主机</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form id="editZjForm">
                            <input type="hidden" id="editZjId" name="id">
                            <div class="form-group">
                                <label for="editZjUser">用户名</label>
                                <input type="text" class="form-control" id="editZjUser" name="user" required>
                            </div>
                            <div class="form-group">
                                <label for="editZjPass">密码</label>
                                <input type="password" class="form-control" id="editZjPass" name="pass" required>
                            </div>
                            <div class="form-group">
                                <label for="editZjCplx">类型</label>
                                <input type="text" class="form-control" id="editZjCplx" name="cplx" required>
                            </div>
                            <div class="form-group">
                                <label for="editZjWypj">网页空间 (MB)</label>
                                <input type="number" class="form-control" id="editZjWypj" name="wypj" min="1" required>
                            </div>
                            <div class="form-group">
                                <label for="editZjSypj">数据库空间 (MB)</label>
                                <input type="number" class="form-control" id="editZjSypj" name="sypj" min="1" required>
                            </div>
                            <div class="form-group">
                                <label for="editZjLlxz">流量 (GB)</label>
                                <input type="number" class="form-control" id="editZjLlxz" name="llxz" min="1" required>
                            </div>
                            <div class="form-group">
                                <label for="editZjDqsj">到期时间</label>
                                <input type="date" class="form-control" id="editZjDqsj" name="dqsj" required>
                            </div>
                            <div class="form-group">
                                <label for="editZjYms">域名数</label>
                                <input type="number" class="form-control" id="editZjYms" name="yms" min="0" required>
                                <small class="form-text text-muted">0表示不限制域名绑定数量</small>
                            </div>
                            <div class="form-group">
                                <label for="editZjBtid">宝塔服务器</label>
                                <select class="form-control" id="editZjBtid" name="btid" required>
                                    <?php
                                    $bts = $DB->query("SELECT * FROM `bt` ORDER BY `id` DESC");
                                    while ($bt = $DB->fetch($bts)) {
                                        echo '<option value="' . $bt['id'] . '">' . $bt['ip'] . ':' . $bt['dk'] . '</option>';
                                    }
                                    ?>
                                </select>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                        <button type="button" class="btn btn-primary" onclick="saveEditZj()">保存</button>
                    </div>
                </div>
            </div>
        </div>
        
        <script>
        var zjState = {page: 1, limit: 10, total: 0};

        function escapeZjHtml(text) {
            if (text === null || text === undefined) return '';
            return String(text).replace(/[&<>\"]/g, function(match) {
                return {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;'}[match];
            });
        }

        function renderZjRows(rows) {
            if (!rows || rows.length === 0) {
                $('#zj-body').html('<tr><td colspan="10" class="text-center text-muted">暂无主机记录</td></tr>');
                return;
            }
            var html = '';
            // 检测是否为手机端（在循环外部检测一次）
            var isMobile = window.innerWidth <= 768;
            
            rows.forEach(function(row) {
                var statusBadge = row.zt === '正常' ? '<span class="badge badge-success">正常</span>' : '<span class="badge badge-danger">' + escapeZjHtml(row.zt || '-') + '</span>';
                
                // 手机端使用纯图标按钮，桌面端使用图标+文字
                var loginBtn, editBtn, deleteBtn, toggleBtn;
                var mobileStyle = 'style="min-width:28px!important;min-height:28px!important;width:28px!important;height:28px!important;padding:0!important;margin:2px!important;font-size:0!important;display:inline-flex!important;align-items:center!important;justify-content:center!important;border-radius:4px!important;"';
                var mobileIconStyle = 'style="font-size:12px!important;margin:0!important;"';
                // 根据状态决定暂停/启动按钮
                var isRunning = row.zt === '正常';
                var toggleBtnClass = isRunning ? 'btn-secondary' : 'btn-info';
                var toggleBtnIcon = isRunning ? 'fa-pause' : 'fa-play';
                var toggleBtnText = isRunning ? '暂停' : '启动';
                var toggleBtnTitle = isRunning ? '暂停网站' : '启动网站';
                
                if (isMobile) {
                    loginBtn = '<button class="btn btn-success btn-sm zj-login" ' + mobileStyle + ' data-user="' + escapeZjHtml(row.user) + '" data-pass="' + escapeZjHtml(row.pass) + '" title="登录"><i class="fas fa-sign-in-alt" ' + mobileIconStyle + '></i></button>';
                    toggleBtn = '<button class="btn ' + toggleBtnClass + ' btn-sm zj-toggle" ' + mobileStyle + ' data-id="' + escapeZjHtml(row.id) + '" data-user="' + escapeZjHtml(row.user) + '" data-action="' + (isRunning ? 'stop' : 'start') + '" title="' + toggleBtnTitle + '"><i class="fas ' + toggleBtnIcon + '" ' + mobileIconStyle + '></i></button>';
                    editBtn = '<button class="btn btn-warning btn-sm zj-edit" ' + mobileStyle + ' data-id="' + escapeZjHtml(row.id) + '" data-user="' + escapeZjHtml(row.user) + '" data-pass="' + escapeZjHtml(row.pass) + '" data-cplx="' + escapeZjHtml(row.cplx) + '" data-wypj="' + escapeZjHtml(row.wypj) + '" data-sypj="' + escapeZjHtml(row.sypj) + '" data-llxz="' + escapeZjHtml(row.llxz) + '" data-dqsj="' + escapeZjHtml(row.dqsj) + '" data-yms="' + escapeZjHtml(row.yms) + '" data-btid="' + escapeZjHtml(row.btid) + '" title="编辑"><i class="fas fa-edit" ' + mobileIconStyle + '></i></button>';
                    deleteBtn = '<button class="btn btn-danger btn-sm zj-delete" ' + mobileStyle + ' data-id="' + escapeZjHtml(row.id) + '" title="删除"><i class="fas fa-trash-alt" ' + mobileIconStyle + '></i></button>';
                } else {
                    loginBtn = '<button class="btn btn-success btn-sm zj-login" data-user="' + escapeZjHtml(row.user) + '" data-pass="' + escapeZjHtml(row.pass) + '" title="登录用户面板"><i class="fas fa-sign-in-alt"></i> 登录</button>';
                    toggleBtn = '<button class="btn ' + toggleBtnClass + ' btn-sm zj-toggle" data-id="' + escapeZjHtml(row.id) + '" data-user="' + escapeZjHtml(row.user) + '" data-action="' + (isRunning ? 'stop' : 'start') + '"><i class="fas ' + toggleBtnIcon + '"></i> ' + toggleBtnText + '</button>';
                    editBtn = '<button class="btn btn-warning btn-sm zj-edit" data-id="' + escapeZjHtml(row.id) + '" data-user="' + escapeZjHtml(row.user) + '" data-pass="' + escapeZjHtml(row.pass) + '" data-cplx="' + escapeZjHtml(row.cplx) + '" data-wypj="' + escapeZjHtml(row.wypj) + '" data-sypj="' + escapeZjHtml(row.sypj) + '" data-llxz="' + escapeZjHtml(row.llxz) + '" data-dqsj="' + escapeZjHtml(row.dqsj) + '" data-yms="' + escapeZjHtml(row.yms) + '" data-btid="' + escapeZjHtml(row.btid) + '"><i class="fas fa-edit"></i> 编辑</button>';
                    deleteBtn = '<button class="btn btn-danger btn-sm zj-delete" data-id="' + escapeZjHtml(row.id) + '"><i class="fas fa-trash-alt"></i> 删除</button>';
                }
                
                html += '<tr>' +
                    '<td><input type="checkbox" class="zj-check" value="' + escapeZjHtml(row.id) + '"></td>' +
                    '<td>' + escapeZjHtml(row.id) + '</td>' +
                    '<td>' + escapeZjHtml(row.user || '-') + '</td>' +
                    '<td>' + escapeZjHtml(row.cplx || '-') + '</td>' +
                    '<td>' + escapeZjHtml(row.wypj || 0) + 'MB</td>' +
                    '<td>' + escapeZjHtml(row.sypj || 0) + 'MB</td>' +
                    '<td>' + escapeZjHtml(row.llxz || 0) + 'GB</td>' +
                    '<td>' + escapeZjHtml(row.dqsj || '-') + '</td>' +
                    '<td>' + statusBadge + '</td>' +
                    '<td>' + loginBtn + toggleBtn + editBtn + deleteBtn + '</td>' +
                    '</tr>';
            });
            $('#zj-body').html(html);
        }

        function renderZjPagination(containerId, state, onPage) {
            var totalPages = Math.max(1, Math.ceil(state.total / state.limit));
            var current = state.page;
            var html = '';
            var start = Math.max(1, current - 2);
            var end = Math.min(totalPages, current + 2);

            html += '<button class="page-btn" ' + (current === 1 ? 'disabled' : '') + ' data-page="' + (current - 1) + '">上一页</button>';
            for (var i = start; i <= end; i++) {
                html += '<button class="page-btn ' + (i === current ? 'active' : '') + '" data-page="' + i + '">' + i + '</button>';
            }
            html += '<button class="page-btn" ' + (current === totalPages ? 'disabled' : '') + ' data-page="' + (current + 1) + '">下一页</button>';
            $('#' + containerId).html(html);
            $('#' + containerId + ' .page-btn').off('click').on('click', function() {
                var page = parseInt($(this).data('page'), 10);
                if (!isNaN(page) && page >= 1 && page <= totalPages && page !== current) {
                    onPage(page);
                }
            });
        }

        function loadZjList(page) {
            zjState.page = page || zjState.page;
            $('#zj-body').html('<tr><td colspan="10" class="text-center text-muted">加载中...</td></tr>');

            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {
                    egn: 'listzj',
                    page: zjState.page,
                    limit: zjState.limit,
                    keyword: $('#zj-keyword').val()
                },
                dataType: 'json',
                success: function(data) {
                    zjState.total = data.total || 0;
                    renderZjRows(data.rows || []);
                    renderZjPagination('zj-pagination', zjState, loadZjList);
                },
                error: function() {
                    $('#zj-body').html('<tr><td colspan="10" class="text-center text-muted">加载失败，请重试</td></tr>');
                }
            });
        }

        function editzj(id, user, pass, cplx, wypj, sypj, llxz, dqsj, yms, btid) {
            $('#editZjId').val(id);
            $('#editZjUser').val(user);
            $('#editZjPass').val(pass);
            $('#editZjCplx').val(cplx);
            // 数据库中存储的是MB，直接显示
            $('#editZjWypj').val(wypj);
            $('#editZjSypj').val(sypj);
            $('#editZjLlxz').val(llxz);
            $('#editZjDqsj').val(dqsj);
            $('#editZjYms').val(yms);
            $('#editZjBtid').val(btid);
            $('#editZjModal').modal('show');
        }
        
        function saveEditZj() {
            var id = $('#editZjId').val();
            var user = $('#editZjUser').val();
            var pass = $('#editZjPass').val();
            var cplx = $('#editZjCplx').val();
            // 数据库中存储的是MB，直接保存
            var wypj = $('#editZjWypj').val();
            var sypj = $('#editZjSypj').val();
            var llxz = $('#editZjLlxz').val();
            var dqsj = $('#editZjDqsj').val();
            var yms = $('#editZjYms').val();
            var btid = $('#editZjBtid').val();
            
            if (!user || !pass || !cplx || !wypj || !sypj || !llxz || !dqsj || !yms || !btid) {
                alert('请填写所有必填字段');
                return;
            }
            
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {egn: 'edit_zj', id: id, user: user, pass: pass, cplx: cplx, wypj: wypj, sypj: sypj, llxz: llxz, dqsj: dqsj, yms: yms, btid: btid},
                dataType: 'json',
                success: function(data) {
                    alert(data.code);
                    if(data.code == '编辑成功') {
                        $('#editZjModal').modal('hide');
                        loadZjList(zjState.page);
                    }
                },
                error: function() {
                    alert('操作失败，请重试');
                }
            });
        }
        
        function delzj(id) {
            if(confirm('确定要删除这个主机吗？')) {
                $.ajax({
                    type: 'POST',
                    url: 'ajax.php',
                    data: {egn: 'zjsc', id: id},
                    dataType: 'json',
                    success: function(data) {
                        alert(data.code);
                        if(data.code == '删除成功') {
                            loadZjList(1);
                        }
                    },
                    error: function() {
                        alert('操作失败，请重试');
                    }
                });
            }
        }

        function batchDeleteZj(ids) {
            if (!ids || ids.length === 0) {
                alert('请选择要删除的主机');
                return;
            }
            if (!confirm('确定要删除选中的主机吗？')) return;
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {egn: 'zjscxz', idsz: ids},
                dataType: 'json',
                success: function(data) {
                    alert(data.code || '操作完成');
                    loadZjList(1);
                },
                error: function() {
                    alert('操作失败，请重试');
                }
            });
        }

        function exportZj(ids) {
            var form = $('<form>', {method: 'post', action: 'ajax.php', target: '_blank'});
            form.append($('<input>', {type: 'hidden', name: 'egn', value: 'exportzj'}));
            form.append($('<input>', {type: 'hidden', name: 'keyword', value: $('#zj-keyword').val()}));
            if (ids && ids.length > 0) {
                form.append($('<input>', {type: 'hidden', name: 'ids', value: ids.join(',')}));
            }
            $('body').append(form);
            form.submit();
            form.remove();
        }

        $(document).ready(function() {
            loadZjList(1);

            $('#zj-search').on('click', function() { loadZjList(1); });
            $('#zj-reset').on('click', function() {
                $('#zj-keyword').val('');
                loadZjList(1);
            });
            $('#zj-refresh').on('click', function() { loadZjList(zjState.page); });
            $('#zj-export').on('click', function() {
                var ids = $('.zj-check:checked').map(function() { return $(this).val(); }).get();
                exportZj(ids);
            });
            $('#zj-batch-delete').on('click', function() {
                var ids = $('.zj-check:checked').map(function() { return $(this).val(); }).get();
                batchDeleteZj(ids);
            });
            $('#zj-check-all').on('change', function() {
                $('.zj-check').prop('checked', $(this).is(':checked'));
            });
            $('#zj-table').on('click', '.zj-delete', function() {
                delzj($(this).data('id'));
            });
            $('#zj-table').on('click', '.zj-edit', function() {
                editzj($(this).data('id'), $(this).data('user'), $(this).data('pass'), $(this).data('cplx'), $(this).data('wypj'), $(this).data('sypj'), $(this).data('llxz'), $(this).data('dqsj'), $(this).data('yms'), $(this).data('btid'));
            });
            $('#zj-table').on('click', '.zj-login', function() {
                var user = $(this).data('user');
                var pass = $(this).data('pass');
                if(confirm('确定要以用户 ' + user + ' 的身份登录到用户面板吗？')) {
                    // 创建表单并提交
                    var form = $('<form>', {
                        'action': '/user/login.php',
                        'method': 'POST',
                        'target': '_blank'
                    });
                    form.append($('<input>', {'type': 'hidden', 'name': 'user', 'value': user}));
                    form.append($('<input>', {'type': 'hidden', 'name': 'pass', 'value': pass}));
                    form.append($('<input>', {'type': 'hidden', 'name': 'admin_login', 'value': '1'}));
                    $('body').append(form);
                    form.submit();
                    form.remove();
                }
            });
            $('#zj-table').on('click', '.zj-toggle', function() {
                var id = $(this).data('id');
                var user = $(this).data('user');
                var action = $(this).data('action');
                var actionText = action === 'stop' ? '暂停' : '启动';
                
                if(confirm('确定要' + actionText + '用户 ' + user + ' 的网站吗？')) {
                    $.ajax({
                        type: 'POST',
                        url: 'ajax.php',
                        data: {
                            egn: 'toggle_site',
                            id: id,
                            action: action
                        },
                        dataType: 'json',
                        success: function(data) {
                            if(data.code === 1 || data.status === true) {
                                alert(actionText + '成功！');
                                loadZjList(zjState.page);
                            } else {
                                alert(actionText + '失败：' + (data.msg || '未知错误'));
                            }
                        },
                        error: function() {
                            alert('请求失败，请重试');
                        }
                    });
                }
            });
        });
        </script>
        
        <?php elseif ($gn == 'dd'): ?>
        <div class="card">
            <h3><i class="fas fa-receipt"></i> 订单列表</h3>
            <div class="table-toolbar">
                <div class="toolbar-left">
                    <button class="btn btn-danger btn-sm" id="dd-batch-delete"><i class="fas fa-trash-alt"></i> 删除选中</button>
                    <button class="btn btn-secondary btn-sm" id="dd-export"><i class="fas fa-file-export"></i> 导出CSV</button>
                    <button class="btn btn-info btn-sm" id="dd-refresh"><i class="fas fa-sync"></i> 刷新</button>
                </div>
                <div class="toolbar-right">
                    <input type="text" class="form-control form-control-sm" id="dd-keyword" placeholder="订单号/用户/商品">
                    <select class="form-control form-control-sm" id="dd-status">
                        <option value="">全部状态</option>
                        <option value="paid">已支付</option>
                        <option value="pending">待支付</option>
                        <option value="failed">支付失败</option>
                        <option value="cancelled">已取消</option>
                    </select>
                    <select class="form-control form-control-sm" id="dd-payment">
                        <option value="">全部支付</option>
                        <option value="alipay">支付宝</option>
                        <option value="wechat">微信</option>
                    </select>
                    <button class="btn btn-primary btn-sm" id="dd-search"><i class="fas fa-search"></i> 查询</button>
                    <button class="btn btn-light btn-sm" id="dd-reset"><i class="fas fa-redo"></i> 重置</button>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table" id="dd-table">
                    <thead>
                        <tr>
                            <th style="width: 40px;"><input type="checkbox" id="dd-check-all"></th>
                            <th>ID</th>
                            <th>用户</th>
                            <th>订单号</th>
                            <th>商品</th>
                            <th>金额</th>
                            <th>支付方式</th>
                            <th>状态</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="dd-body">
                        <tr><td colspan="10" class="text-center text-muted">加载中...</td></tr>
                    </tbody>
                </table>
            </div>
            <div class="pagination" id="dd-pagination"></div>
        </div>
        <script>
        var ddState = {page: 1, limit: 10, total: 0};

        function escapeHtml(text) {
            if (text === null || text === undefined) return '';
            return String(text).replace(/[&<>"]/g, function(match) {
                return {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;'}[match];
            });
        }

        function renderDdRows(rows) {
            if (!rows || rows.length === 0) {
                $('#dd-body').html('<tr><td colspan="10" class="text-center text-muted">暂无订单记录</td></tr>');
                return;
            }
            var html = '';
            rows.forEach(function(row) {
                var statusClass = 'badge-warning';
                var statusText = row.status || '-';
                if (row.status === 'paid' || row.status === '已支付') {
                    statusClass = 'badge-success';
                    statusText = '已支付';
                } else if (row.status === 'pending' || row.status === '待支付') {
                    statusClass = 'badge-warning';
                    statusText = '待支付';
                } else if (row.status === 'failed' || row.status === '支付失败') {
                    statusClass = 'badge-danger';
                    statusText = '支付失败';
                } else if (row.status === 'cancelled' || row.status === '已取消') {
                    statusClass = 'badge-secondary';
                    statusText = '已取消';
                }
                html += '<tr>' +
                    '<td><input type="checkbox" class="dd-check" value="' + escapeHtml(row.id) + '"></td>' +
                    '<td>' + escapeHtml(row.id) + '</td>' +
                    '<td>' + escapeHtml(row.user) + '</td>' +
                    '<td>' + escapeHtml(row.order_no) + '</td>' +
                    '<td>' + escapeHtml(row.product_name) + '</td>' +
                    '<td>¥' + escapeHtml(row.amount) + '</td>' +
                    '<td>' + escapeHtml(row.payment_method) + '</td>' +
                    '<td><span class="badge ' + statusClass + '">' + escapeHtml(statusText) + '</span></td>' +
                    '<td>' + escapeHtml(row.create_time) + '</td>' +
                    '<td><button class="btn btn-danger btn-sm dd-delete" data-id="' + escapeHtml(row.id) + '"><i class="fas fa-trash-alt"></i> 删除</button></td>' +
                    '</tr>';
            });
            $('#dd-body').html(html);
        }

        function renderPagination(containerId, state, onPage) {
            var totalPages = Math.max(1, Math.ceil(state.total / state.limit));
            var current = state.page;
            var html = '';
            var start = Math.max(1, current - 2);
            var end = Math.min(totalPages, current + 2);

            html += '<button class="page-btn" ' + (current === 1 ? 'disabled' : '') + ' data-page="' + (current - 1) + '">上一页</button>';
            for (var i = start; i <= end; i++) {
                html += '<button class="page-btn ' + (i === current ? 'active' : '') + '" data-page="' + i + '">' + i + '</button>';
            }
            html += '<button class="page-btn" ' + (current === totalPages ? 'disabled' : '') + ' data-page="' + (current + 1) + '">下一页</button>';
            $('#' + containerId).html(html);
            $('#' + containerId + ' .page-btn').off('click').on('click', function() {
                var page = parseInt($(this).data('page'), 10);
                if (!isNaN(page) && page >= 1 && page <= totalPages && page !== current) {
                    onPage(page);
                }
            });
        }

        function loadDdList(page) {
            ddState.page = page || ddState.page;
            var keyword = $('#dd-keyword').val();
            var status = $('#dd-status').val();
            var payment = $('#dd-payment').val();
            $('#dd-body').html('<tr><td colspan="10" class="text-center text-muted">加载中...</td></tr>');

            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {
                    egn: 'listdd',
                    page: ddState.page,
                    limit: ddState.limit,
                    keyword: keyword,
                    status: status,
                    payment_method: payment
                },
                dataType: 'json',
                success: function(data) {
                    ddState.total = data.total || 0;
                    renderDdRows(data.rows || []);
                    renderPagination('dd-pagination', ddState, loadDdList);
                },
                error: function() {
                    $('#dd-body').html('<tr><td colspan="10" class="text-center text-muted">加载失败，请重试</td></tr>');
                }
            });
        }

        function deleteDd(id) {
            if (!id) return;
            if (!confirm('确定要删除该订单记录吗？')) return;
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {egn: 'ddsc', id: id},
                dataType: 'json',
                success: function(data) {
                    alert(data.code || '操作完成');
                    if (data.code == '删除成功') {
                        loadDdList(1);
                    }
                },
                error: function() {
                    alert('操作失败，请重试');
                }
            });
        }

        function batchDeleteDd(ids) {
            if (!ids || ids.length === 0) {
                alert('请选择要删除的订单');
                return;
            }
            if (!confirm('确定要删除选中的订单记录吗？')) return;
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {egn: 'ddscxz', idsz: ids},
                dataType: 'json',
                success: function(data) {
                    alert(data.code || '操作完成');
                    if (data.code == '删除成功') {
                        loadDdList(1);
                    }
                },
                error: function() {
                    alert('操作失败，请重试');
                }
            });
        }

        function exportDd(ids) {
            var form = $('<form>', {method: 'post', action: 'ajax.php', target: '_blank'});
            form.append($('<input>', {type: 'hidden', name: 'egn', value: 'exportdd'}));
            form.append($('<input>', {type: 'hidden', name: 'keyword', value: $('#dd-keyword').val()}));
            form.append($('<input>', {type: 'hidden', name: 'status', value: $('#dd-status').val()}));
            form.append($('<input>', {type: 'hidden', name: 'payment_method', value: $('#dd-payment').val()}));
            if (ids && ids.length > 0) {
                form.append($('<input>', {type: 'hidden', name: 'ids', value: ids.join(',')}));
            }
            $('body').append(form);
            form.submit();
            form.remove();
        }

        $(document).ready(function() {
            loadDdList(1);

            $('#dd-search').on('click', function() { loadDdList(1); });
            $('#dd-reset').on('click', function() {
                $('#dd-keyword').val('');
                $('#dd-status').val('');
                $('#dd-payment').val('');
                loadDdList(1);
            });
            $('#dd-refresh').on('click', function() { loadDdList(ddState.page); });
            $('#dd-export').on('click', function() {
                var ids = $('.dd-check:checked').map(function() { return $(this).val(); }).get();
                exportDd(ids);
            });
            $('#dd-batch-delete').on('click', function() {
                var ids = $('.dd-check:checked').map(function() { return $(this).val(); }).get();
                batchDeleteDd(ids);
            });
            $('#dd-check-all').on('change', function() {
                $('.dd-check').prop('checked', $(this).is(':checked'));
            });
            $('#dd-table').on('click', '.dd-delete', function() {
                deleteDd($(this).data('id'));
            });
        });
        </script>

        <?php elseif ($gn == 'cx'): ?>
        <?php
        // 获取所有分类
        $categories = array();
        $cat_res = $DB->query("SELECT * FROM `program_categories` ORDER BY `sort_order` ASC, `id` ASC");
        while ($cr = $DB->fetch($cat_res)) {
            $categories[] = $cr;
        }
        ?>
        <div class="card">
            <h3><i class="fas fa-box"></i> 程序列表</h3>
            <div class="table-toolbar">
                <div class="toolbar-left">
                    <a href="add.php?gn=cx" class="btn btn-primary btn-sm"><i class="fas fa-plus"></i> 添加程序</a>
                    <a href="add.php?gn=dr" class="btn btn-secondary btn-sm"><i class="fas fa-file-import"></i> 导入程序</a>
                    <button class="btn btn-danger btn-sm" id="cx-batch-delete"><i class="fas fa-trash-alt"></i> 删除选中</button>
                    <button class="btn btn-success btn-sm" id="cx-export"><i class="fas fa-file-archive"></i> 导出程序</button>
                    <button class="btn btn-info btn-sm" id="cx-refresh"><i class="fas fa-sync"></i> 刷新</button>
                    <div id="export-status" style="display: none; margin-left: 10px; color: #28a745; font-size: 14px;"></div>
                    <div class="d-inline-block ml-2">
                        <select class="form-control form-control-sm d-inline-block" id="cx-category-select" style="width: 150px;">
                            <option value="">选择分类...</option>
                            <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo htmlspecialchars($cat['name']); ?>"><?php echo htmlspecialchars($cat['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <button class="btn btn-warning btn-sm" id="cx-batch-update-category"><i class="fas fa-tags"></i> 更新分类</button>
                    </div>
                </div>
                <div class="toolbar-right">
                    <input type="text" class="form-control form-control-sm" id="cx-keyword" placeholder="程序名称/类型/版本">
                    <div class="btn-group">
                        <button class="btn btn-primary btn-sm" id="cx-search"><i class="fas fa-search"></i> 查询</button>
                        <button class="btn btn-light btn-sm" id="cx-reset"><i class="fas fa-redo"></i> 重置</button>
                    </div>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table table-hover" id="cx-table" style="table-layout: fixed;">
                    <thead>
                        <tr>
                            <th style="width: 40px; text-align: center;"><input type="checkbox" id="cx-check-all"></th>
                            <th style="width: 50px; text-align: center;">ID</th>
                            <th style="width: 280px;">程序名称</th>
                            <th style="width: 100px; text-align: center;">类型</th>
                            <th style="width: 80px; text-align: center;">价格</th>
                            <th style="width: 130px; text-align: center;">空间需求</th>
                            <th style="width: auto;">简介</th>
                            <th style="width: 70px; text-align: center;">状态</th>
                            <th style="width: 130px; text-align: center;">操作</th>
                        </tr>
                    </thead>
                    <tbody id="cx-body">
                        <tr><td colspan="9" class="text-center text-muted">加载中...</td></tr>
                    </tbody>
                </table>
            </div>
            <div class="pagination" id="cx-pagination"></div>
        </div>
        <script>
        var cxState = {page: 1, limit: 10, total: 0};

        // 确保escapeHtml函数可用
        function escapeHtml(text) {
            if (text === null || text === undefined) return '';
            return String(text).replace(/[&<>"]/g, function(match) {
                return {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;'}[match];
            });
        }

        function renderCxRows(rows) {
            if (!rows || rows.length === 0) {
                $('#cx-body').html('<tr><td colspan="9" class="text-center text-muted">暂无程序</td></tr>');
                return;
            }
            var html = '';
            rows.forEach(function(row) {
                // 状态标签
                var statusBadge = row.status == 1 
                    ? '<span class="badge badge-success">上架</span>' 
                    : '<span class="badge badge-secondary">下架</span>';
                
                // 空间信息
                var spaceInfo = '';
                if (row.webkj || row.sqlkj) {
                    spaceInfo = '<div style="line-height: 1.4;">';
                    if (row.webkj) spaceInfo += '<div><i class="fas fa-globe text-muted" style="width: 14px;"></i> <small>Web: ' + row.webkj + 'MB</small></div>';
                    if (row.sqlkj) spaceInfo += '<div><i class="fas fa-database text-muted" style="width: 14px;"></i> <small>DB: ' + row.sqlkj + 'MB</small></div>';
                    spaceInfo += '</div>';
                }
                
                // 操作按钮
                var actionBtns = '<div class="btn-group btn-group-sm">' +
                    '<button class="btn btn-info cx-edit" data-id="' + escapeHtml(row.id) + '" title="编辑"><i class="fas fa-edit"></i></button>' +
                    '<button class="btn btn-warning cx-toggle" data-id="' + escapeHtml(row.id) + '" data-status="' + row.status + '" title="' + (row.status == 1 ? '下架' : '上架') + '"><i class="fas fa-' + (row.status == 1 ? 'eye-slash' : 'eye') + '"></i></button>' +
                    '<button class="btn btn-danger cx-delete" data-id="' + escapeHtml(row.id) + '" title="删除"><i class="fas fa-trash-alt"></i></button>' +
                    '</div>';
                
                // 图片预览 - 支持 tb(封面)、cover、images 字段
                var imagePreview = '';
                var coverImg = row.tb || row.cover || '';
                var images = [];
                try {
                    if (row.images && typeof row.images === 'string') {
                        images = JSON.parse(row.images);
                    }
                } catch (e) {
                    images = [];
                }
                if (images.length > 0) {
                    imagePreview = '<div class="program-images-preview" style="position: relative; display: inline-block; flex-shrink: 0;">' +
                        '<img src="/uploads/' + escapeHtml(images[0]) + '" class="rounded" style="width: 60px; height: 60px; object-fit: cover; cursor: pointer; border: 1px solid #e0e0e0;" onclick="showImageGallery(' + row.id + ', \'' + escapeHtml(row.images).replace(/\\/g, '\\\\') + '\')">';
                    if (images.length > 1) {
                        imagePreview += '<span class="image-count" style="position: absolute; bottom: 2px; right: 2px; background: rgba(0,0,0,0.7); color: white; font-size: 10px; padding: 1px 5px; border-radius: 10px;">+' + (images.length - 1) + '</span>';
                    }
                    imagePreview += '</div>';
                } else if (coverImg) {
                    imagePreview = '<img src="/uploads/' + escapeHtml(coverImg) + '" class="rounded" style="width: 60px; height: 60px; object-fit: cover; border: 1px solid #e0e0e0; flex-shrink: 0;">';
                } else {
                    imagePreview = '<div class="rounded bg-light d-flex align-items-center justify-content-center" style="width: 60px; height: 60px; border: 1px solid #e0e0e0; flex-shrink: 0;"><i class="fas fa-image text-muted" style="font-size: 20px;"></i></div>';
                }
                
                html += '<tr style="vertical-align: middle;">' +
                    '<td style="text-align: center;"><input type="checkbox" class="cx-check" value="' + escapeHtml(row.id) + '"></td>' +
                    '<td style="text-align: center;"><span class="badge badge-light">' + escapeHtml(row.id) + '</span></td>' +
                    '<td style="overflow: hidden;">' +
                        '<div class="d-flex align-items-center" style="min-width: 0;">' +
                            imagePreview +
                            '<div style="margin-left: 12px; min-width: 0; flex: 1;">' +
                                '<div class="font-weight-500 text-truncate" style="font-size: 14px; color: #333;" title="' + escapeHtml(row.name) + '">' + escapeHtml(row.name) + '</div>' +
                                '<small class="text-muted" style="font-size: 12px;">v' + escapeHtml(row.version) + '</small>' +
                            '</div>' +
                        '</div>' +
                    '</td>' +
                    '<td style="text-align: center;"><span class="badge badge-info">' + escapeHtml(row.type) + '</span></td>' +
                    '<td style="text-align: center;"><span class="text-primary font-weight-bold">¥' + escapeHtml(row.price) + '</span></td>' +
                    '<td style="text-align: center;">' + spaceInfo + '</td>' +
                    '<td style="max-width: 250px; overflow: hidden;"><small class="text-muted text-truncate d-block" title="' + escapeHtml(row.desc) + '">' + escapeHtml(row.desc ? row.desc.substring(0, 60) + '...' : '-') + '</small></td>' +
                    '<td style="text-align: center;">' + statusBadge + '</td>' +
                    '<td style="text-align: center;">' + actionBtns + '</td>' +
                    '</tr>';
            });
            $('#cx-body').html(html);
        }

        function loadCxList(page) {
            cxState.page = page || cxState.page;
            var keyword = $('#cx-keyword').val();
            $('#cx-body').html('<tr><td colspan="8" class="text-center text-muted">加载中...</td></tr>');

            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {
                    egn: 'listbs',
                    page: cxState.page,
                    limit: cxState.limit,
                    keyword: keyword
                },
                dataType: 'json',
                success: function(data) {
                    cxState.total = data.total || 0;
                    renderCxRows(data.rows || []);
                    renderPagination('cx-pagination', cxState, loadCxList);
                },
                error: function(xhr, status, error) {
                    $('#cx-body').html('<tr><td colspan="9" class="text-center text-muted">加载失败: ' + (xhr.responseText || '请检查网络') + '</td></tr>');
                }
            });
        }

        function deleteCx(id) {
            if (!id) return;
            if (!confirm('确定要删除该程序吗？')) return;
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {egn: 'bssc', id: id},
                dataType: 'json',
                success: function(data) {
                    alert(data.code || '操作完成');
                    if (data.code == '删除成功') {
                        loadCxList(1);
                    }
                },
                error: function() {
                    alert('操作失败，请重试');
                }
            });
        }

        function batchDeleteCx(ids) {
            if (!ids || ids.length === 0) {
                alert('请选择要删除的程序');
                return;
            }
            if (!confirm('确定要删除选中的程序吗？')) return;
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {egn: 'bsscxz', idsz: ids},
                dataType: 'json',
                success: function(data) {
                    alert(data.code || '操作完成');
                    if (data.code == '删除成功') {
                        loadCxList(1);
                    }
                },
                error: function() {
                    alert('操作失败，请重试');
                }
            });
        }

        function exportCx(ids) {
            if (!ids || ids.length === 0) {
                alert('请先选择要导出的程序');
                return;
            }

            $('#export-status').show().text('正在导出...');

            // 使用AJAX请求获取导出结果
            var form = $('<form>', {method: 'post', action: 'ajax.php'});
            form.append($('<input>', {type: 'hidden', name: 'egn', value: 'exportbs'}));
            form.append($('<input>', {type: 'hidden', name: 'ids', value: ids.join(',')}));
            form.append($('<input>', {type: 'hidden', name: 'keyword', value: $('#cx-keyword').val()}));

            // 使用隐藏的iframe来处理文件下载
            var iframe = $('<iframe>', {
                name: 'export_iframe',
                style: 'display: none'
            });
            $('body').append(iframe);
            form.attr('target', 'export_iframe');

            // 设置超时，防止iframe load事件不触发
            var timeout = setTimeout(function() {
                $('#export-status').text('导出完成！');
                setTimeout(function() {
                    $('#export-status').hide();
                    iframe.remove();
                }, 2000);
            }, 10000);

            // 监听iframe加载完成事件
            iframe.one('load', function() {
                clearTimeout(timeout);
                try {
                    // 尝试读取iframe内容
                    var iframeContent = iframe.contents().find('body').html();
                    if (iframeContent) {
                        // 如果返回的是JSON错误信息
                        try {
                            var response = JSON.parse(iframeContent);
                            if (response.code && response.code !== '成功') {
                                $('#export-status').text('导出失败: ' + response.code);
                                setTimeout(function() {
                                    $('#export-status').hide();
                                    iframe.remove();
                                }, 5000);
                                return;
                            }
                        } catch (e) {
                            // 不是JSON，可能是文件下载
                        }
                    }
                } catch (e) {
                    // 无法读取iframe内容，可能是跨域或文件下载
                }
                
                $('#export-status').text('导出完成！');
                setTimeout(function() {
                    $('#export-status').hide();
                    iframe.remove();
                }, 2000);
            });

            $('body').append(form);
            console.log('表单已提交');
            form.submit();
            form.remove();
        }

        function batchUpdateCategory(ids) {
            if (!ids || ids.length === 0) {
                alert('请选择要更新的程序');
                return;
            }
            var category = $('#cx-category-select').val();
            if (!category) {
                alert('请选择要更新的分类');
                return;
            }
            if (!confirm('确定要将选中的 ' + ids.length + ' 个程序更新为分类 "' + category + '" 吗？')) return;
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {egn: 'update_category', ids: ids.join(','), category: category},
                dataType: 'json',
                success: function(data) {
                    alert(data.code || '操作完成');
                    if (data.code == '更新成功') {
                        loadCxList(cxState.page);
                        $('#cx-category-select').val('');
                    }
                },
                error: function() {
                    alert('操作失败，请重试');
                }
            });
        }

        $(document).ready(function() {
            loadCxList(1);

            $('#cx-search').on('click', function() { loadCxList(1); });
            $('#cx-reset').on('click', function() { $('#cx-keyword').val(''); loadCxList(1); });
            $('#cx-refresh').on('click', function() { loadCxList(cxState.page); });
            $('#cx-export').on('click', function() {
                var ids = $('.cx-check:checked').map(function() { return $(this).val(); }).get();
                exportCx(ids);
            });
            $('#cx-batch-delete').on('click', function() {
                var ids = $('.cx-check:checked').map(function() { return $(this).val(); }).get();
                batchDeleteCx(ids);
            });
            $('#cx-batch-update-category').on('click', function() {
                var ids = $('.cx-check:checked').map(function() { return $(this).val(); }).get();
                batchUpdateCategory(ids);
            });
            $('#cx-check-all').on('change', function() {
                $('.cx-check').prop('checked', $(this).is(':checked'));
            });
            $('#cx-table').on('click', '.cx-delete', function() {
                deleteCx($(this).data('id'));
            });
            $('#cx-table').on('click', '.cx-edit', function() {
                var id = $(this).data('id');
                if (window.parent && window.parent.loadPage) {
                    window.parent.loadPage('edit.php?gn=cx&id=' + id);
                } else {
                    window.location.href = 'edit.php?gn=cx&id=' + id;
                }
            });
            $('#cx-table').on('click', '.cx-toggle', function() {
                var id = $(this).data('id');
                var currentStatus = $(this).data('status');
                var newStatus = currentStatus == 1 ? 0 : 1;
                var actionText = newStatus == 1 ? '上架' : '下架';
                if (!confirm('确定要' + actionText + '该程序吗？')) return;
                $.ajax({
                    type: 'POST',
                    url: 'ajax.php',
                    data: {egn: 'toggle_status', id: id, status: newStatus},
                    dataType: 'json',
                    success: function(data) {
                        alert(data.code || '操作完成');
                        loadCxList(cxState.page);
                    },
                    error: function() {
                        alert('操作失败，请重试');
                    }
                });
            });
        });
        
        // 图片画廊查看功能
        function showImageGallery(programId, imagesJson) {
            var images = JSON.parse(imagesJson);
            if (images.length === 0) return;
            
            var carouselHtml = '<div id="imageCarousel" class="carousel slide" data-ride="carousel">';
            
            // 指示器
            carouselHtml += '<ol class="carousel-indicators">';
            for (var i = 0; i < images.length; i++) {
                carouselHtml += '<li data-target="#imageCarousel" data-slide-to="' + i + '"' + (i === 0 ? ' class="active"' : '') + '></li>';
            }
            carouselHtml += '</ol>';
            
            // 图片项
            carouselHtml += '<div class="carousel-inner">';
            for (var i = 0; i < images.length; i++) {
                carouselHtml += '<div class="carousel-item' + (i === 0 ? ' active' : '') + '">';
                carouselHtml += '<img src="../uploads/' + escapeHtml(images[i]) + '" class="d-block w-100" style="max-height: 500px; object-fit: contain; background: #f8f9fa;">';
                carouselHtml += '</div>';
            }
            carouselHtml += '</div>';
            
            // 控制按钮
            if (images.length > 1) {
                carouselHtml += '<a class="carousel-control-prev" href="#imageCarousel" role="button" data-slide="prev">';
                carouselHtml += '<span class="carousel-control-prev-icon"></span>';
                carouselHtml += '</a>';
                carouselHtml += '<a class="carousel-control-next" href="#imageCarousel" role="button" data-slide="next">';
                carouselHtml += '<span class="carousel-control-next-icon"></span>';
                carouselHtml += '</a>';
            }
            
            carouselHtml += '</div>';
            
            // 创建模态框
            var modalHtml = '<div class="modal fade" id="imageGalleryModal" tabindex="-1" role="dialog">';
            modalHtml += '<div class="modal-dialog modal-lg" role="document">';
            modalHtml += '<div class="modal-content">';
            modalHtml += '<div class="modal-header">';
            modalHtml += '<h5 class="modal-title">程序图片展示 (' + images.length + '张)</h5>';
            modalHtml += '<button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>';
            modalHtml += '</div>';
            modalHtml += '<div class="modal-body">' + carouselHtml + '</div>';
            modalHtml += '</div>';
            modalHtml += '</div>';
            modalHtml += '</div>';
            
            // 移除已存在的模态框
            $('#imageGalleryModal').remove();
            
            // 添加模态框到页面并显示
            $('body').append(modalHtml);
            $('#imageGalleryModal').modal('show');
        }

        function renderPagination(containerId, state, onPage) {
            var totalPages = Math.max(1, Math.ceil(state.total / state.limit));
            var current = state.page;
            var html = '';
            var start = Math.max(1, current - 2);
            var end = Math.min(totalPages, current + 2);

            html += '<button class="page-btn" ' + (current === 1 ? 'disabled' : '') + ' data-page="' + (current - 1) + '">上一页</button>';
            for (var i = start; i <= end; i++) {
                html += '<button class="page-btn" ' + (i === current ? 'active' : '') + '" data-page="' + i + '">' + i + '</button>';
            }
            html += '<button class="page-btn" ' + (current === totalPages ? 'disabled' : '') + ' data-page="' + (current + 1) + '">下一页</button>';
            $('#' + containerId).html(html);
            $('#' + containerId + ' .page-btn').off('click').on('click', function() {
                var page = parseInt($(this).data('page'), 10);
                if (!isNaN(page) && page >= 1 && page <= totalPages && page !== current) {
                    onPage(page);
                }
            });
        }
        </script>

        <?php elseif (in_array($gn, ['admin_log', 'user_log', 'host_log', 'api_log'])): ?>
        <?php
        $logTypes = [
            'admin_log' => ['title' => '管理员日志', 'icon' => 'fa-user-shield', 'type' => 'admin'],
            'user_log' => ['title' => '用户日志', 'icon' => 'fa-users', 'type' => 'user'],
            'host_log' => ['title' => '开通日志', 'icon' => 'fa-server', 'type' => 'host'],
            'api_log' => ['title' => 'API调用日志', 'icon' => 'fa-code', 'type' => 'api']
        ];
        $currentLog = $logTypes[$gn];
        $isHostLog = ($gn === 'host_log');
        ?>
        <div class="card">
            <h3><i class="fas <?php echo $currentLog['icon']; ?>"></i> <?php echo $currentLog['title']; ?></h3>
            <div class="table-toolbar">
                <div class="toolbar-left">
                    <button class="btn btn-danger btn-sm" id="log-batch-delete"><i class="fas fa-trash-alt"></i> 删除选中</button>
                    <button class="btn btn-warning btn-sm" id="log-clear-all"><i class="fas fa-trash"></i> 清空全部</button>
                    <button class="btn btn-secondary btn-sm" id="log-refresh"><i class="fas fa-sync"></i> 刷新</button>
                </div>
                <div class="toolbar-right">
                    <input type="text" class="form-control form-control-sm" id="log-keyword" placeholder="<?php echo $isHostLog ? '用户名/域名/套餐' : '用户名/操作内容'; ?>">
                    <button class="btn btn-primary btn-sm" id="log-search"><i class="fas fa-search"></i> 查询</button>
                    <button class="btn btn-light btn-sm" id="log-reset"><i class="fas fa-redo"></i> 重置</button>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table" id="log-table">
                    <thead>
                        <tr>
                            <th style="width: 40px;"><input type="checkbox" id="log-check-all"></th>
                            <th>ID</th>
                            <th>用户名</th>
                            <?php if ($isHostLog): ?>
                            <th>操作类型</th>
                            <th>域名</th>
                            <th>套餐</th>
                            <th>价格</th>
                            <th>时长</th>
                            <th>IP地址</th>
                            <th>时间</th>
                            <?php else: ?>
                            <th>操作类型</th>
                            <th>操作内容</th>
                            <th>IP地址</th>
                            <th>时间</th>
                            <?php endif; ?>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="log-body">
                        <tr><td colspan="<?php echo $isHostLog ? '11' : '8'; ?>" class="text-center text-muted">加载中...</td></tr>
                    </tbody>
                </table>
            </div>
            <div class="pagination" id="log-pagination"></div>
        </div>
        
        <script>
        var logState = {page: 1, limit: 10, total: 0, type: '<?php echo $currentLog['type']; ?>'};

        function escapeLogHtml(text) {
            if (text === null || text === undefined) return '';
            return String(text).replace(/[&<>"]/g, function(match) {
                return {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;'}[match];
            });
        }

        function renderLogRows(rows) {
            if (!rows || rows.length === 0) {
                var colspan = logState.type === 'host' ? '11' : '8';
                $('#log-body').html('<tr><td colspan="' + colspan + '" class="text-center text-muted">暂无日志记录</td></tr>');
                return;
            }
            var html = '';
            var isHost = logState.type === 'host';
            rows.forEach(function(row) {
                if (isHost) {
                    // 开通日志格式
                    html += '<tr>' +
                        '<td><input type="checkbox" class="log-check" value="' + escapeLogHtml(row.id) + '"></td>' +
                        '<td>' + escapeLogHtml(row.id) + '</td>' +
                        '<td>' + escapeLogHtml(row.user || '-') + '</td>' +
                        '<td>' + escapeLogHtml(row.lx || '-') + '</td>' +
                        '<td>' + escapeLogHtml(row.hostname || '-') + '</td>' +
                        '<td>' + escapeLogHtml(row.package || '-') + '</td>' +
                        '<td>¥' + escapeLogHtml(row.price || '0.00') + '</td>' +
                        '<td>' + escapeLogHtml(row.duration || '0') + '个月</td>' +
                        '<td>' + escapeLogHtml(row.ip || '-') + '</td>' +
                        '<td>' + escapeLogHtml(row.date || '-') + '</td>' +
                        '<td>' +
                        '<button class="btn btn-danger btn-sm log-delete" data-id="' + escapeLogHtml(row.id) + '"><i class="fas fa-trash-alt"></i> 删除</button>' +
                        '</td>' +
                        '</tr>';
                } else {
                    // 普通日志格式
                    html += '<tr>' +
                        '<td><input type="checkbox" class="log-check" value="' + escapeLogHtml(row.id) + '"></td>' +
                        '<td>' + escapeLogHtml(row.id) + '</td>' +
                        '<td>' + escapeLogHtml(row.user || '-') + '</td>' +
                        '<td>' + escapeLogHtml(row.lx || '-') + '</td>' +
                        '<td>' + escapeLogHtml(row.lr || '-') + '</td>' +
                        '<td>' + escapeLogHtml(row.ip || '-') + '</td>' +
                        '<td>' + escapeLogHtml(row.date || '-') + '</td>' +
                        '<td>' +
                        '<button class="btn btn-danger btn-sm log-delete" data-id="' + escapeLogHtml(row.id) + '"><i class="fas fa-trash-alt"></i> 删除</button>' +
                        '</td>' +
                        '</tr>';
                }
            });
            $('#log-body').html(html);
        }

        function renderLogPagination(containerId, state, onPage) {
            var totalPages = Math.max(1, Math.ceil(state.total / state.limit));
            var current = state.page;
            var html = '';
            var start = Math.max(1, current - 2);
            var end = Math.min(totalPages, current + 2);

            html += '<button class="page-btn" ' + (current === 1 ? 'disabled' : '') + ' data-page="' + (current - 1) + '">上一页</button>';
            for (var i = start; i <= end; i++) {
                html += '<button class="page-btn ' + (i === current ? 'active' : '') + '" data-page="' + i + '">' + i + '</button>';
            }
            html += '<button class="page-btn" ' + (current === totalPages ? 'disabled' : '') + ' data-page="' + (current + 1) + '">下一页</button>';
            $('#' + containerId).html(html);
            $('#' + containerId + ' .page-btn').off('click').on('click', function() {
                var page = parseInt($(this).data('page'), 10);
                if (!isNaN(page) && page >= 1 && page <= totalPages && page !== current) {
                    onPage(page);
                }
            });
        }

        function loadLogList(page) {
            logState.page = page || logState.page;
            var colspan = logState.type === 'host' ? '11' : '8';
            $('#log-body').html('<tr><td colspan="' + colspan + '" class="text-center text-muted">加载中...</td></tr>');

            $.ajax({
                type: 'POST',
                url: 'ajax.php?t=' + new Date().getTime(),
                data: {
                    egn: 'listlog',
                    page: logState.page,
                    limit: logState.limit,
                    keyword: $('#log-keyword').val(),
                    type: logState.type
                },
                dataType: 'json',
                cache: false,
                success: function(data) {
                    logState.total = data.total || 0;
                    renderLogRows(data.rows || []);
                    renderLogPagination('log-pagination', logState, loadLogList);
                    $('#log-check-all').prop('checked', false);
                },
                error: function() {
                    $('#log-body').html('<tr><td colspan="' + colspan + '" class="text-center text-muted">加载失败，请重试</td></tr>');
                }
            });
        }

        function deleteLog(id) {
            if (!confirm('确定要删除该日志吗？')) return;
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {egn: 'deletelog', id: id, type: logState.type},
                dataType: 'json',
                success: function(data) {
                    if (data.code === 0) {
                        alert('删除成功');
                        loadLogList(logState.page);
                    } else {
                        alert(data.message || '删除失败');
                    }
                },
                error: function(xhr, status, error) {
                    alert('删除失败: ' + (error || '网络错误'));
                }
            });
        }

        function batchDeleteLog(ids) {
            if (!ids || ids.length === 0) {
                alert('请选择要删除的日志');
                return;
            }
            if (!confirm('确定要删除选中的 ' + ids.length + ' 条日志吗？')) return;
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {egn: 'batch_deletelog', ids: ids.join(','), type: logState.type},
                dataType: 'json',
                success: function(data) {
                    if (data.code === 0) {
                        alert('成功删除 ' + (data.count || ids.length) + ' 条日志');
                        loadLogList(1);
                    } else {
                        alert(data.message || '删除失败');
                    }
                },
                error: function(xhr, status, error) {
                    alert('删除失败: ' + (error || '网络错误'));
                }
            });
        }

        function clearAllLogs() {
            if (!confirm('确定要清空所有日志吗？\n\n此操作不可恢复！请谨慎操作！')) return;
            if (!confirm('再次确认：真的要清空所有日志吗？')) return;
            
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {egn: 'clearlog', type: logState.type},
                dataType: 'json',
                success: function(data) {
                    if (data.code === 0) {
                        alert('清空成功');
                        loadLogList(1);
                    } else {
                        alert(data.message || '清空失败');
                    }
                },
                error: function(xhr, status, error) {
                    alert('清空失败: ' + (error || '网络错误'));
                }
            });
        }

        $(document).ready(function() {
            loadLogList(1);

            $('#log-search').on('click', function() { loadLogList(1); });
            $('#log-reset').on('click', function() { $('#log-keyword').val(''); loadLogList(1); });
            $('#log-refresh').on('click', function() { loadLogList(logState.page); });
            $('#log-batch-delete').on('click', function() {
                var ids = $('.log-check:checked').map(function() { return $(this).val(); }).get();
                batchDeleteLog(ids);
            });
            $('#log-clear-all').on('click', function() {
                clearAllLogs();
            });
            $('#log-check-all').on('change', function() {
                $('.log-check').prop('checked', $(this).is(':checked'));
            });
            $('#log-table').on('click', '.log-delete', function() {
                deleteLog($(this).data('id'));
            });
        });
        </script>
        <?php endif; ?>
    </div>
</body>
</html>
