<?php
/**
 * @file: index.php
 * @version: 1.0.0
 * @last_modified: 'git' is not recognized as an internal or external command,
operable program or batch file.
 * @author: 开发团队
 * 
 * @description:
 * Index functionality
 * 
 * @functions:
 * - selectTable(): [Add description]
 * - validateField(): [Add description]
 * - showError(): [Add description]
 * - loadSearchFields(): [Add description]
 * 
 * @dependencies:
 * - App\Database
 * - ($db) {
                return $db->escapeIdentifier($field['field_name'])
 * 
 * @changelog:
 * - 1.0.0 ('git' is not recognized as an internal or external command,
operable program or batch file.): Initial version
 */

require_once 'includes/autoload.php';
use App\Database;

// 初始化应用程序
if (!initializeApplication()) {
    die("系统初始化失败");
}
$db = Database::getInstance();

// 获取系统配置 - 优化查询，一次性获取所有需要的配置
$configKeys = ['site_title', 'theme_color', 'theme_style', 'site_footer', 'default_page_size'];
$placeholders = array_fill(0, count($configKeys), '?');
$configs = $db->fetchAll(
    "SELECT config_key, config_value FROM sys_configs WHERE config_key IN (" . implode(',', $placeholders) . ")",
    $configKeys
);

// 构建配置映射
$siteConfig = [];
foreach ($configs as $config) {
    $siteConfig[$config['config_key']] = $config['config_value'];
}

// 设置默认值
$siteTitle = $siteConfig['site_title'] ?? '通用查询系统';
$themeColor = $siteConfig['theme_color'] ?? '#667eea';
$themeStyle = $siteConfig['theme_style'] ?? 'gradient';
$siteFooter = $siteConfig['site_footer'] ?? '© 2025 通用查询系统 All Rights Reserved';
$pageSize = intval($siteConfig['default_page_size'] ?? 10);

// 生成渐变色（如果是渐变风格）
$gradientColor2 = '#764ba2'; // 默认渐变色
if ($themeStyle === 'gradient') {
    // 根据主题色生成渐变色
    $rgb = sscanf($themeColor, "#%02x%02x%02x");
    if ($rgb) {
        $r = max(0, min(255, $rgb[0] + 20));
        $g = max(0, min(255, $rgb[1] - 20));
        $b = max(0, min(255, $rgb[2] + 30));
        $gradientColor2 = sprintf("#%02x%02x%02x", $r, $g, $b);
    }
}

// 获取可用的数据表 - 优化查询，使用JOIN一次性获取所有信息
$tables = $db->fetchAll("
    SELECT t.id, t.table_name, t.table_title, t.table_description,
           COUNT(f.id) as field_count
    FROM data_tables t
    LEFT JOIN data_fields f ON t.id = f.table_id
    WHERE t.show_in_homepage = 1 AND t.is_active = 1
    GROUP BY t.id
    ORDER BY t.sort_order ASC, t.created_at DESC
");

// 处理查询请求
$searchResults = [];
$searchTableId = 0;
$searchTableInfo = null;
$searchFields = [];
$totalRecords = 0;
$currentPage = 1;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['search_table_id'])) {
    $searchTableId = intval($_POST['search_table_id']);
    
    // 获取表信息和字段配置 - 优化：使用一次查询获取所有需要的信息
    $tableData = $db->fetchAll("
        SELECT 
            t.id as table_id, t.table_name, t.table_title, t.table_description,
            f.id as field_id, f.field_name, f.field_title, f.field_type, 
            f.field_length, f.is_searchable, f.is_displayable, f.sort_order,
            f.validation_rules, f.placeholder_text, f.help_text, f.input_type, f.is_required, f.options
        FROM data_tables t
        LEFT JOIN data_fields f ON t.id = f.table_id
        WHERE t.id = ? AND t.show_in_homepage = 1 AND t.is_active = 1
        ORDER BY f.sort_order, f.id
    ", [$searchTableId]);
    
    if (!empty($tableData)) {
        // 提取表信息
        $searchTableInfo = [
            'id' => $tableData[0]['table_id'],
            'table_name' => $tableData[0]['table_name'],
            'table_title' => $tableData[0]['table_title'],
            'table_description' => $tableData[0]['table_description']
        ];
        
        // 提取字段信息
        $tableFields = [];
        foreach ($tableData as $row) {
            if ($row['field_id']) {
                $tableFields[] = [
                    'id' => $row['field_id'],
                    'field_name' => $row['field_name'],
                    'field_title' => $row['field_title'],
                    'field_type' => $row['field_type'],
                    'field_length' => $row['field_length'],
                    'is_searchable' => $row['is_searchable'],
                    'is_displayable' => $row['is_displayable'],
                    'sort_order' => $row['sort_order'],
                    'validation_rules' => $row['validation_rules'],
                    'placeholder_text' => $row['placeholder_text'],
                    'help_text' => $row['help_text'],
                    'input_type' => $row['input_type'],
                    'is_required' => $row['is_required'],
                    'options' => $row['options']
                ];
            }
        }
        
        $searchTable = $searchTableInfo['table_name'];
        
        // 构建查询条件
        $whereConditions = [];
        $params = [];
        $hasValidSearch = false;
        
        // 清除之前的验证错误
        unset($_SESSION['validation_errors']);
        
        foreach ($tableFields as $field) {
            if ($field['is_searchable'] && !empty($_POST[$field['field_name']])) {
                $value = cleanInput($_POST[$field['field_name']]);
                
                // 后端数据验证
                $isValid = true;
                $errorMsg = '';
                
                // 类型验证
                switch ($field['field_type']) {
                    case 'int':
                    case 'integer':
                    case 'bigint':
                    case 'tinyint':
                    case 'smallint':
                    case 'mediumint':
                        if (!is_numeric($value)) {
                            $isValid = false;
                            $errorMsg = $field['field_title'] . ' 必须是数字';
                        }
                        break;
                    case 'float':
                    case 'double':
                    case 'decimal':
                        if (!is_numeric($value)) {
                            $isValid = false;
                            $errorMsg = $field['field_title'] . ' 必须是数字';
                        }
                        break;
                    case 'varchar':
                    case 'char':
                        if ($field['field_length'] && mb_strlen($value) > $field['field_length']) {
                            $isValid = false;
                            $errorMsg = $field['field_title'] . ' 长度不能超过 ' . $field['field_length'] . ' 个字符';
                        }
                        break;
                }
                
                if (!$isValid) {
                    // 记录验证错误
                    if (!isset($_SESSION['validation_errors'])) {
                        $_SESSION['validation_errors'] = [];
                    }
                    $_SESSION['validation_errors'][$field['field_name']] = $errorMsg;
                    continue;
                }
                
                // 精确查询
                $whereConditions[] = $db->escapeIdentifier($field['field_name']) . " = ?";
                $params[] = $value;
                $hasValidSearch = true;
            }
        }
        
        if ($hasValidSearch && !empty($whereConditions)) {
            // 获取显示字段
            $displayFields = array_filter($tableFields, function($field) {
                return $field['is_displayable'];
            });
            
            // 构建查询字段列表
            $selectFields = array_map(function($field) use ($db) {
                return $db->escapeIdentifier($field['field_name']);
            }, $displayFields);
            
            // 如果没有显示字段，至少显示主键
            if (empty($selectFields)) {
                $selectFields = ['*'];
            } else {
                $selectSql = implode(', ', $selectFields);
            }
            
            $whereSql = implode(' AND ', $whereConditions);
            
            // 分页处理 - 使用优化的分页服务
            $currentPage = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
            
            // 使用查询构建器优化查询
            $queryBuilder = $db->createQueryBuilder($searchTable);
            
            // 添加查询条件
            foreach ($tableFields as $field) {
                if ($field['is_searchable'] && !empty($_POST[$field['field_name']])) {
                    $value = cleanInput($_POST[$field['field_name']]);
                    if (!isset($_SESSION['validation_errors'][$field['field_name']])) {
                        $queryBuilder->where($field['field_name'], '=', $value);
                    }
                }
            }
            
            // 设置查询字段
            if (!empty($selectFields) && $selectFields[0] !== '*') {
                $queryBuilder->select(array_map(function($field) {
                    return $field['field_name'];
                }, $displayFields));
            }
            
            // 使用高性能分页查询
            $paginationResult = $queryBuilder->paginate($currentPage, $pageSize, 'auto');
            $searchResults = $paginationResult['data'];
            $totalRecords = $paginationResult['pagination']['total'];
            $searchFields = $displayFields;
            
            // 验证实际结果数量，确保统计准确性
            if (!empty($searchResults)) {
                $actualCount = count($searchResults);
                // 如果是第一页且结果数量与总数不符，重新计算总数
                if ($currentPage == 1 && $actualCount > 0) {
                    // 构建相同的查询条件来重新计算总数
                    $countQuery = "SELECT COUNT(*) as total FROM `{$searchTable}` WHERE {$whereSql}";
                    $countResult = $db->fetchOne($countQuery, $params);
                    if ($countResult && $countResult['total'] != $totalRecords) {
                        $totalRecords = $countResult['total'];
                    }
                }
            }
            
            // 记录查询日志
            $db->logAction('FRONTEND_SEARCH', $searchTable, "前台查询表: {$searchTable}, 找到 {$totalRecords} 条记录");
        }
    }
}

// 获取搜索字段 - 优化：缓存查询结果
$searchableFields = [];
if ($searchTableId > 0) {
    // 使用之前查询的数据，避免重复查询
    if (!empty($tableFields)) {
        $searchableFields = array_filter($tableFields, function($field) {
            return $field['is_searchable'];
        });
    } else {
        // 如果没有POST请求，才需要查询
        $searchableFields = $db->fetchAll("
            SELECT f.* 
            FROM data_fields f
            INNER JOIN data_tables t ON f.table_id = t.id
            WHERE f.table_id = ? 
            AND f.is_searchable = 1 
            AND t.show_in_homepage = 1 
            AND t.is_active = 1
            ORDER BY f.sort_order
        ", [$searchTableId]);
    }
}

// 获取验证错误
$validationErrors = $_SESSION['validation_errors'] ?? [];
unset($_SESSION['validation_errors']);
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($siteTitle) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.0/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        :root {
            --theme-color: <?= htmlspecialchars($themeColor) ?>;
            --theme-color-rgb: <?php 
                $rgb = sscanf($themeColor, "#%02x%02x%02x");
                echo $rgb ? "{$rgb[0]}, {$rgb[1]}, {$rgb[2]}" : "102, 126, 234";
            ?>;
            --gradient-color-2: <?= htmlspecialchars($gradientColor2) ?>;
        }
        
        body { 
            background-color: #f0f2f5; 
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .navbar {
            <?php if ($themeStyle === 'gradient'): ?>
            background: linear-gradient(135deg, var(--theme-color) 0%, var(--gradient-color-2) 100%);
            <?php else: ?>
            background: var(--theme-color);
            <?php endif; ?>
            box-shadow: 0 2px 15px rgba(var(--theme-color-rgb), 0.2);
        }
        
        .search-container,
        .result-container { 
            background: white; 
            border-radius: 15px; 
            box-shadow: 0 5px 20px rgba(0,0,0,0.08);
            border: 1px solid #e8e8e8;
            transition: all 0.3s ease;
        }
        
        .search-container:hover,
        .result-container:hover {
            box-shadow: 0 8px 30px rgba(0,0,0,0.12);
            transform: translateY(-2px);
        }
        
        .result-card {
            background: #ffffff;
            border: 1px solid #e9ecef;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 15px;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .result-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 20px rgba(var(--theme-color-rgb), 0.2);
            border-color: var(--theme-color);
        }
        
        .field-row {
            display: flex;
            padding: 12px 0;
            border-bottom: 1px solid #f0f0f0;
            transition: all 0.2s ease;
        }
        
        .field-row:last-child {
            border-bottom: none;
        }
        
        .field-label {
            font-weight: 600;
            color: #495057;
            min-width: 150px;
            padding-right: 20px;
        }
        
        .field-value {
            color: #212529;
            flex: 1;
            word-break: break-word;
        }
        
        .navbar-brand { 
            font-weight: bold; 
            font-size: 1.4rem;
        }
        
        .btn-primary {
            <?php if ($themeStyle === 'gradient'): ?>
            background: linear-gradient(135deg, var(--theme-color) 0%, var(--gradient-color-2) 100%);
            <?php else: ?>
            background: var(--theme-color);
            <?php endif; ?>
            border: none;
            transition: all 0.3s ease;
            border-radius: 8px;
            padding: 10px 20px;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(var(--theme-color-rgb), 0.4);
            <?php if ($themeStyle === 'gradient'): ?>
            background: linear-gradient(135deg, var(--gradient-color-2) 0%, var(--theme-color) 100%);
            <?php else: ?>
            background: var(--theme-color);
            filter: brightness(1.1);
            <?php endif; ?>
        }
        
        .form-control, .form-select {
            border-radius: 8px;
            border: 1.5px solid #e0e0e0;
            transition: all 0.3s ease;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--theme-color);
            box-shadow: 0 0 0 0.2rem rgba(var(--theme-color-rgb), 0.15);
        }
        
        .form-control.is-invalid {
            border-color: #dc3545;
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e");
            background-repeat: no-repeat;
            background-position: right calc(.375em + .1875rem) center;
            background-size: calc(.75em + .375rem) calc(.75em + .375rem);
        }
        
        .invalid-feedback {
            display: block;
            font-size: .875em;
            color: #dc3545;
            margin-top: .25rem;
        }
        
        .badge-count {
            <?php if ($themeStyle === 'gradient' || $themeStyle === 'modern'): ?>
            background: linear-gradient(135deg, var(--theme-color) 0%, var(--gradient-color-2) 100%);
            <?php elseif ($themeStyle === 'vibrant'): ?>
            background: linear-gradient(45deg, var(--theme-color) 0%, var(--gradient-color-2) 100%);
            box-shadow: 0 2px 6px rgba(var(--theme-color-rgb), 0.3);
            <?php else: ?>
            background: var(--theme-color); 
            <?php endif; ?>
            color: white;
            padding: 4px 8px;
            border-radius: <?= $themeStyle === 'minimal' ? '3px' : ($themeStyle === 'vibrant' ? '8px' : '5px') ?>;
            font-size: 0.75rem;
            font-weight: 500;
            display: inline-block;
            line-height: 1.2;
        }
        
        .record-badge {
            <?php if ($themeStyle === 'gradient'): ?>
            background: linear-gradient(135deg, var(--theme-color) 0%, var(--gradient-color-2) 100%);
            <?php else: ?>
            background: var(--theme-color);
            <?php endif; ?>
            color: white;
            padding: 4px 12px;
            border-radius: 4px;
            font-size: 0.85rem;
        }
        
        .table-option {
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .table-option:hover {
            border-color: var(--theme-color);
            background-color: #f8f9fa;
        }
        
        .table-option.selected {
            border-color: var(--theme-color);
            background-color: rgba(var(--theme-color-rgb), 0.05);
        }
        
        .table-option h6 {
            margin: 0;
            color: #333;
        }
        
        .table-option small {
            color: #666;
        }
        
        .table-description {
            font-size: 0.85rem;
            color: #6c757d;
            margin-top: 5px;
        }
        
        @media print {
            /* 隐藏不需要打印的元素 */
            .no-print,
            .section-title {
                display: none !important;
            }
            
            /* 显示打印专用元素 */
            .print-header,
            .print-record-header {
                display: block !important;
            }
            
            /* 页面基础样式 */
            body {
                background: white !important;
                color: #000 !important;
                font-family: "Microsoft YaHei", Arial, sans-serif;
                font-size: 12px;
                line-height: 1.4;
                margin: 0;
                padding: 15px;
            }
            
            /* 去掉最外层卡片效果 */
            .result-container {
                background: none !important;
                border: none !important;
                box-shadow: none !important;
                border-radius: 0 !important;
                padding: 0 !important;
                margin: 0 !important;
            }
            
            /* 打印表头样式 */
            .print-header {
                margin-bottom: 25px;
                padding-bottom: 15px;
            }
            
            .print-title h2 {
                font-size: 20px;
                font-weight: bold;
                margin: 0 0 5px 0;
                text-align: center;
                color: #000;
            }
            
            .print-subtitle {
                font-size: 14px;
                text-align: center;
                color: #666;
                margin-bottom: 15px;
            }
            
            .print-info {
                display: table;
                width: 100%;
                border-collapse: collapse;
            }
            
            .print-info-row {
                display: table-row;
                border-bottom: 1px solid #eee;
            }
            
            .print-info-label,
            .print-info-value {
                display: table-cell;
                padding: 6px 8px;
                vertical-align: top;
            }
            
            .print-info-label {
                width: 80px;
                font-weight: bold;
                background-color: #f8f9fa;
                border-right: 1px solid #eee;
            }
            
            .print-info-value {
                background-color: white;
            }
            
            .print-divider {
                border: none;
                border-top: 1px solid #666666;
                margin: 15px 0;
            }
            
            /* 记录卡片样式 */
            .result-card {
                page-break-inside: avoid;
                border: 1px solid #666666;
                margin-bottom: 20px;
                padding: 0;
                background: white;
                border-radius: 0;
                box-shadow: none;
            }
            
            /* 打印记录标题 */
            .print-record-header {
                background-color: #2c5aa0;
                color: white;
                padding: 8px 12px;
                margin: 0;
                font-weight: bold;
                font-size: 13px;
            }
            
            .print-record-title {
                margin: 0;
                font-size: 13px;
                font-weight: bold;
            }
            
            /* 字段行样式 */
            .field-row {
                display: table-row;
                border-bottom: 1px solid #eee;
            }
            
            .field-label,
            .field-value {
                display: table-cell;
                padding: 8px 12px;
                vertical-align: top;
                border: none;
            }
            
            .field-label {
                width: 120px;
                font-weight: bold;
                background-color: #f8f9fa;
                border-right: 1px solid #eee;
                color: #333;
            }
            
            .field-value {
                background-color: white;
                color: #000;
                word-break: break-all;
            }
            
            /* 隐藏标题行的容器 */
            .d-flex.justify-content-between.align-items-center.mb-4 {
                display: none !important;
            }
            
            /* 分页隐藏 */
            .pagination,
            .page-info {
                display: none !important;
            }
            
            /* 确保表格样式 */
            .result-card .field-row:first-child .field-label,
            .result-card .field-row:first-child .field-value {
                border-top: none;
            }
            
            .result-card .field-row:last-child {
                border-bottom: none;
            }
            
            /* 页面分页控制 */
            .result-card {
                page-break-after: auto;
            }
            
            /* 避免在字段中间分页 */
            .field-row {
                page-break-inside: avoid;
            }
        }
        
        .section-title {
            position: relative;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }
        
        .section-title::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 50px;
            height: 3px;
            <?php if ($themeStyle === 'gradient'): ?>
            background: linear-gradient(135deg, var(--theme-color) 0%, var(--gradient-color-2) 100%);
            <?php else: ?>
            background: var(--theme-color);
            <?php endif; ?>
            border-radius: 2px;
        }
        
        .alert-info {
            background-color: rgba(var(--theme-color-rgb), 0.1);
            border-color: var(--theme-color);
            color: #004085;
            border-radius: 10px;
        }
        
        .pagination .page-link {
            color: var(--theme-color);
            border-radius: 5px;
            margin: 0 2px;
            transition: all 0.3s ease;
        }
        
        .pagination .page-link:hover {
            background-color: var(--theme-color);
            color: white;
            transform: translateY(-2px);
        }
        
        .pagination .page-item.active .page-link {
            background-color: var(--theme-color);
            border-color: var(--theme-color);
        }
        
        /* 添加加载动画 */
        .form-control:disabled {
            background-color: #f5f5f5;
            cursor: not-allowed;
        }
        
        /* 搜索结果动画 */
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .result-card {
            animation: slideIn 0.5s ease-out;
        }
        
        /* 加载中动画 */
        .loading-spinner {
            display: none;
            text-align: center;
            padding: 20px;
        }
        
        .loading-spinner.show {
            display: block;
        }
        
        .spinner-border {
            color: var(--theme-color) !important;
        }
        
        /* 优化移动端显示 */
        @media (max-width: 768px) {
            .field-row {
                flex-direction: column;
            }
            
            .field-label {
                min-width: auto;
                margin-bottom: 5px;
            }
        }
        
        /* 页脚样式 */
        .footer {
            background-color: #f8f9fa;
            padding: 20px 0;
            margin-top: 50px;
            border-top: 1px solid #e9ecef;
            color: #6c757d;
            text-align: center;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark no-print">
        <div class="container">
            <a class="navbar-brand" href="index.php">
                <i class="bi bi-search-heart"></i> <?= htmlspecialchars($siteTitle) ?>
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="admin/login.php">
                    <i class="bi bi-person-circle"></i> 管理员登录
                </a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-lg-4 col-md-5 no-print">
                <div class="search-container p-4 mb-4">
                    <h5 class="section-title"><i class="bi bi-funnel"></i> 查询条件</h5>
                    
                    <form method="post" id="searchForm" novalidate>
                        <div class="mb-3">
                            <label class="form-label fw-bold">选择查询表</label>
                            <?php if (!empty($tables)): ?>
                                <div class="table-options">
                                    <?php foreach ($tables as $table): ?>
                                        <div class="table-option <?= $searchTableId == $table['id'] ? 'selected' : '' ?>" 
                                             onclick="selectTable(<?= $table['id'] ?>)">
                                            <input type="radio" name="search_table_id" 
                                                   value="<?= $table['id'] ?>" 
                                                   id="table_<?= $table['id'] ?>"
                                                   <?= $searchTableId == $table['id'] ? 'checked' : '' ?>
                                                   style="display: none;">
                                            <h6><?= htmlspecialchars($table['table_title']) ?></h6>
                                            <small class="text-muted">
                                                <i class="bi bi-table"></i> <?= htmlspecialchars($table['table_name']) ?>
                                                <span class="badge badge-count ms-1"><?= $table['field_count'] ?> 字段</span>
                                            </small>
                                            <?php if ($table['table_description']): ?>
                                                <div class="table-description">
                                                    <?= htmlspecialchars($table['table_description']) ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php else: ?>
                                <div class="alert alert-warning">
                                    <i class="bi bi-exclamation-triangle"></i> 暂无可用的查询表
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <div id="searchFields">
                            <?php if (!empty($searchableFields)): ?>
                                <div class="alert alert-warning alert-sm mb-3">
                                    <i class="bi bi-info-circle"></i> 使用精确查询，请输入完整信息
                                </div>
                                <?php foreach ($searchableFields as $field): ?>
                                    <?php
                                    $hasError = isset($validationErrors[$field['field_name']]);
                                    $errorMsg = $validationErrors[$field['field_name']] ?? '';
                                    $isRequired = isset($field['is_required']) ? $field['is_required'] : false;
                                    $options = isset($field['options']) ? $field['options'] : null;
                                    $placeholderText = isset($field['placeholder_text']) ? $field['placeholder_text'] : '';
                                    ?>
                                    <div class="mb-3">
                                        <label class="form-label">
                                            <?= htmlspecialchars($field['field_title']) ?>
                                            <?php if ($isRequired): ?>
                                                <span class="text-danger">*</span>
                                            <?php endif; ?>
                                        </label>
                                        
                                        <?php if ($field['input_type'] === 'textarea'): ?>
                                            <textarea name="<?= htmlspecialchars($field['field_name']) ?>" 
                                                    class="form-control <?= $hasError ? 'is-invalid' : '' ?>" 
                                                    rows="3"
                                                    placeholder="<?= htmlspecialchars($placeholderText) ?>"
                                                    <?= $isRequired ? 'required' : '' ?>
                                                    data-field-type="<?= $field['field_type'] ?>"
                                                    data-field-length="<?= $field['field_length'] ?>"><?= htmlspecialchars($_POST[$field['field_name']] ?? '') ?></textarea>
                                        <?php elseif ($field['input_type'] === 'select' && $options): ?>
                                            <?php $optionsArray = json_decode($options, true) ?: []; ?>
                                            <select name="<?= htmlspecialchars($field['field_name']) ?>" 
                                                    class="form-select <?= $hasError ? 'is-invalid' : '' ?>"
                                                    <?= $isRequired ? 'required' : '' ?>>
                                                <option value="">请选择</option>
                                                <?php foreach ($optionsArray as $optValue => $optLabel): ?>
                                                    <option value="<?= htmlspecialchars($optValue) ?>"
                                                            <?= ($_POST[$field['field_name']] ?? '') == $optValue ? 'selected' : '' ?>>
                                                        <?= htmlspecialchars($optLabel) ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        <?php elseif ($field['input_type'] === 'number' || in_array($field['field_type'], ['int', 'integer', 'bigint', 'tinyint', 'smallint', 'mediumint'])): ?>
                                            <input type="number" 
                                                   name="<?= htmlspecialchars($field['field_name']) ?>" 
                                                   class="form-control <?= $hasError ? 'is-invalid' : '' ?>"
                                                   placeholder="<?= htmlspecialchars($placeholderText) ?>"
                                                   value="<?= htmlspecialchars($_POST[$field['field_name']] ?? '') ?>"
                                                   <?= $isRequired ? 'required' : '' ?>
                                                   <?= $field['field_length'] ? 'max="' . str_repeat('9', $field['field_length']) . '"' : '' ?>
                                                   data-field-type="<?= $field['field_type'] ?>"
                                                   data-field-length="<?= $field['field_length'] ?>">
                                        <?php elseif ($field['input_type'] === 'date' || $field['field_type'] === 'date'): ?>
                                            <input type="date" 
                                                   name="<?= htmlspecialchars($field['field_name']) ?>" 
                                                   class="form-control <?= $hasError ? 'is-invalid' : '' ?>"
                                                   value="<?= htmlspecialchars($_POST[$field['field_name']] ?? '') ?>"
                                                   <?= $isRequired ? 'required' : '' ?>>
                                        <?php else: ?>
                                            <input type="text" 
                                                   name="<?= htmlspecialchars($field['field_name']) ?>" 
                                                   class="form-control <?= $hasError ? 'is-invalid' : '' ?>"
                                                   placeholder="<?= htmlspecialchars($placeholderText) ?>"
                                                   value="<?= htmlspecialchars($_POST[$field['field_name']] ?? '') ?>"
                                                   <?= $isRequired ? 'required' : '' ?>
                                                   <?= $field['field_length'] ? 'maxlength="' . $field['field_length'] . '"' : '' ?>
                                                   data-field-type="<?= $field['field_type'] ?>"
                                                   data-field-length="<?= $field['field_length'] ?>">
                                        <?php endif; ?>
                                        
                                        <?php if ($hasError): ?>
                                            <div class="invalid-feedback"><?= htmlspecialchars($errorMsg) ?></div>
                                        <?php else: ?>
                                            <div class="invalid-feedback"></div>
                                        <?php endif; ?>
                                        
                                        <?php if (!empty($field['help_text'])): ?>
                                            <small class="text-muted"><?= htmlspecialchars($field['help_text']) ?></small>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>
                                
                                <button type="submit" class="btn btn-primary w-100" id="searchBtn">
                                    <i class="bi bi-search"></i> 立即查询
                                </button>
                                
                                <div class="loading-spinner mt-3">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">查询中...</span>
                                    </div>
                                    <p class="mt-2 text-muted">正在查询，请稍候...</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
            </div>
            
            <div class="col-lg-8 col-md-7">
                <div class="result-container p-4">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h5 class="section-title mb-0"><i class="bi bi-list-check"></i> 查询结果</h5>
                        
                        <?php if (!empty($searchResults)): ?>
                            <div class="export-buttons no-print">
                                <button class="btn btn-sm btn-outline-primary" onclick="window.print()">
                                    <i class="bi bi-printer"></i> 打印
                                </button>
                            </div>
                        <?php endif; ?>
                    </div>
                    
                    <?php if (!empty($searchResults)): ?>
                        <!-- 打印专用表头信息 -->
                        <div class="print-header" style="display: none;">
                            <div class="print-title">
                                <h2><?= htmlspecialchars($siteTitle) ?></h2>
                                <div class="print-subtitle">查询结果报告</div>
                            </div>
                            <div class="print-info">
                                <div class="print-info-row">
                                    <span class="print-info-label">查询表：</span>
                                    <span class="print-info-value"><?= htmlspecialchars($searchTableInfo['table_title'] ?? '') ?></span>
                                </div>
                                <div class="print-info-row">
                                    <span class="print-info-label">查询结果：</span>
                                    <span class="print-info-value">共找到 <?= $totalRecords ?> 条记录</span>
                                </div>
                                <div class="print-info-row">
                                    <span class="print-info-label">查询时间：</span>
                                    <span class="print-info-value"><?= date('Y年m月d日 H时i分s秒') ?></span>
                                </div>
                                <div class="print-info-row">
                                    <span class="print-info-label">查询网址：</span>
                                    <span class="print-info-value"><?= htmlspecialchars($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']) ?></span>
                                </div>
                            </div>
                            <hr class="print-divider">
                        </div>
                        
                        <div class="mb-3 no-print">
                            <small class="text-muted ms-2">
                            共找到 <?= $totalRecords ?> 条记录 | 第 <?= $currentPage ?>/<?= ceil($totalRecords / $pageSize) ?> 页
                            </small>
                        </div>
                        
                        <div id="resultsContent">
                            <?php foreach ($searchResults as $index => $row): ?>
                                <div class="result-card" data-index="<?= $index + 1 ?>">
                                    <!-- 屏幕显示的记录标题 -->
                                    <div class="d-flex justify-content-between align-items-start mb-3 no-print">
                                        <span class="record-badge">记录 #<?= ($currentPage - 1) * $pageSize + $index + 1 ?></span>
                                    </div>
                                    
                                    <!-- 打印专用的记录标题 -->
                                    <div class="print-record-header" style="display: none;">
                                        <div class="print-record-title">记录 #<?= ($currentPage - 1) * $pageSize + $index + 1 ?></div>
                                    </div>
                                    
                                    <!-- 字段数据表格 -->
                                    <div class="fields-table">
                                        <?php foreach ($searchFields as $field): ?>
                                            <div class="field-row">
                                                <div class="field-label"><?= htmlspecialchars($field['field_title']) ?>：</div>
                                                <div class="field-value">
                                                    <?php
                                                    $value = $row[$field['field_name']] ?? '-';
                                                    // 根据字段类型格式化显示
                                                    if ($field['field_type'] === 'date' && $value !== '-' && $value !== null) {
                                                        $value = date('Y年m月d日', strtotime($value));
                                                    } elseif ($field['field_type'] === 'datetime' && $value !== '-' && $value !== null) {
                                                        $value = date('Y年m月d日 H:i:s', strtotime($value));
                                                    } elseif (in_array($field['field_type'], ['float', 'double', 'decimal']) && is_numeric($value)) {
                                                        $value = number_format($value, 2);
                                                    }
                                                    echo htmlspecialchars($value);
                                                    ?>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        
                        <?php 
                        // 使用优化的分页组件
                        if (isset($paginationResult) && $paginationResult['pagination']['last_page'] > 1): 
                            require_once 'classes/Components/PaginationComponent.php';
                            $paginationComponent = new \App\Components\PaginationComponent(
                                $paginationResult['pagination'], 
                                $_SERVER['REQUEST_URI'], 
                                $_GET
                            );
                            echo '<div class="mt-4 no-print">';
                            echo $paginationComponent->render([
                                'show_info' => true,
                                'show_jump' => true,
                                'show_size_selector' => true,
                                'range' => 2
                            ]);
                            echo '</div>';
                        endif; 
                        ?>
                        
                    <?php elseif ($_SERVER['REQUEST_METHOD'] === 'POST'): ?>
                        <div class="alert alert-warning">
                            <i class="bi bi-exclamation-triangle"></i> 未找到符合条件的记录，请检查输入信息是否准确
                        </div>
                    <?php else: ?>
                        <div class="text-center py-5">
                            <i class="bi bi-search" style="font-size: 4rem; color: #dee2e6;"></i>
                            <p class="text-muted mt-3">请先选择查询表并输入查询条件</p>
                            <?php if (empty($tables)): ?>
                                <div class="alert alert-info mt-3">
                                    <i class="bi bi-info-circle"></i> 系统中暂无可用的查询表，请联系管理员配置
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 页脚 -->
    <footer class="footer no-print">
        <div class="container">
            <p class="mb-0"><?= htmlspecialchars($siteFooter) ?></p>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 选择表
        function selectTable(tableId) {
            // 更新选中状态
            document.querySelectorAll('.table-option').forEach(option => {
                option.classList.remove('selected');
            });
            document.querySelector(`#table_${tableId}`).checked = true;
            document.querySelector(`#table_${tableId}`).closest('.table-option').classList.add('selected');
            
            // 自动加载搜索字段
            loadSearchFields();
        }
        
        // 表单验证函数
        function validateField(input) {
            const fieldType = input.getAttribute('data-field-type');
            const fieldLength = input.getAttribute('data-field-length');
            const value = input.value.trim();
            const isRequired = input.hasAttribute('required');
            
            // 清除之前的错误状态
            input.classList.remove('is-invalid');
            const feedback = input.nextElementSibling;
            if (feedback && feedback.classList.contains('invalid-feedback')) {
                feedback.textContent = '';
            }
            
            // 必填验证
            if (isRequired && !value) {
                showError(input, '此字段为必填项');
                return false;
            }
            
            // 如果值为空且非必填，则跳过其他验证
            if (!value) return true;
            
            // 类型验证
            const intTypes = ['int', 'integer', 'bigint', 'tinyint', 'smallint', 'mediumint'];
            const floatTypes = ['float', 'double', 'decimal'];
            
            if (intTypes.includes(fieldType)) {
                if (!/^-?\d+$/.test(value)) {
                    showError(input, '请输入有效的整数');
                    return false;
                }
                // 检查数字位数
                if (fieldLength && value.replace('-', '').length > parseInt(fieldLength)) {
                    showError(input, `数字长度不能超过 ${fieldLength} 位`);
                    return false;
                }
            } else if (floatTypes.includes(fieldType)) {
                if (!/^-?\d*\.?\d+$/.test(value)) {
                    showError(input, '请输入有效的数字');
                    return false;
                }
            } else if ((fieldType === 'varchar' || fieldType === 'char') && fieldLength) {
                if (value.length > parseInt(fieldLength)) {
                    showError(input, `长度不能超过 ${fieldLength} 个字符`);
                    return false;
                }
            }
            
            return true;
        }
        
        // 显示错误信息
        function showError(input, message) {
            input.classList.add('is-invalid');
            const feedback = input.nextElementSibling;
            if (feedback && feedback.classList.contains('invalid-feedback')) {
                feedback.textContent = message;
            }
        }
        
        // 实时验证
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('searchForm');
            if (form) {
                // 为所有输入框添加实时验证
                const inputs = form.querySelectorAll('input[data-field-type], textarea[data-field-type]');
                inputs.forEach(input => {
                    // 输入时验证
                    input.addEventListener('input', function() {
                        validateField(this);
                    });
                    
                    // 失去焦点时验证
                    input.addEventListener('blur', function() {
                        validateField(this);
                    });
                    
                    // 对于数字类型，限制只能输入数字
                    if (['int', 'integer', 'bigint', 'tinyint', 'smallint', 'mediumint'].includes(input.getAttribute('data-field-type'))) {
                        input.addEventListener('keypress', function(e) {
                            const char = String.fromCharCode(e.which);
                            // 允许负号、数字、退格、删除等
                            if (!/[\d-]/.test(char) && e.which !== 8 && e.which !== 46) {
                                e.preventDefault();
                            }
                            // 负号只能在开头
                            if (char === '-' && this.value.length > 0) {
                                e.preventDefault();
                            }
                        });
                    }
                });
                
                // 表单提交时验证
                form.addEventListener('submit', function(e) {
                    let isValid = true;
                    
                    // 检查是否选择了表
                    const selectedTable = document.querySelector('input[name="search_table_id"]:checked');
                    if (!selectedTable) {
                        e.preventDefault();
                        alert('请先选择要查询的表');
                        return;
                    }
                    
                    // 检查是否至少填写了一个搜索条件
                    const searchInputs = form.querySelectorAll('#searchFields input, #searchFields textarea, #searchFields select');
                    let hasSearchValue = false;
                    
                    searchInputs.forEach(input => {
                        if (input.value.trim()) {
                            hasSearchValue = true;
                        }
                        if (!validateField(input)) {
                            isValid = false;
                        }
                    });
                    
                    if (!hasSearchValue) {
                        e.preventDefault();
                        alert('请至少填写一个查询条件');
                        return;
                    }
                    
                    if (!isValid) {
                        e.preventDefault();
                        // 滚动到第一个错误
                        const firstError = form.querySelector('.is-invalid');
                        if (firstError) {
                            firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
                            firstError.focus();
                        }
                    } else {
                        // 显示加载动画
                        document.querySelector('.loading-spinner').classList.add('show');
                        document.getElementById('searchBtn').disabled = true;
                    }
                });
            }
        });
        
        function loadSearchFields() {
            const form = document.getElementById('searchForm');
            const selectedTable = document.querySelector('input[name="search_table_id"]:checked');
            
            if (selectedTable) {
                // 保存当前的查询条件
                const currentValues = {};
                const inputs = form.querySelectorAll('input[type="text"], input[type="number"], textarea, select');
                inputs.forEach(input => {
                    if (input.name && input.name !== 'search_table_id') {
                        currentValues[input.name] = input.value;
                    }
                });
                
                // 提交表单以重新加载搜索字段
                const hiddenInput = document.createElement('input');
                hiddenInput.type = 'hidden';
                hiddenInput.name = 'load_fields';
                hiddenInput.value = '1';
                form.appendChild(hiddenInput);
                
                // 保存查询条件到sessionStorage
                sessionStorage.setItem('searchValues', JSON.stringify(currentValues));
                
                form.submit();
            } else {
                document.getElementById('searchFields').innerHTML = '';
            }
        }
        
        // 页面加载时恢复查询条件
        window.addEventListener('load', function() {
            const savedValues = sessionStorage.getItem('searchValues');
            if (savedValues) {
                const values = JSON.parse(savedValues);
                Object.keys(values).forEach(name => {
                    const input = document.querySelector(`[name="${name}"]`);
                    if (input && values[name]) {
                        input.value = values[name];
                    }
                });
                sessionStorage.removeItem('searchValues');
            }
        });
        
        // 优化打印样式
        window.addEventListener('beforeprint', function() {
            document.body.classList.add('printing');
        });
        
        window.addEventListener('afterprint', function() {
            document.body.classList.remove('printing');
        });
    </script>
</body>
</html>