<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>驾驶舱数据配置管理 - 苏州科技商学院</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/bootstrap-icons/1.11.0/font/bootstrap-icons.css">
    <!-- 自定义样式 -->
    <style>
        :root {
            --primary-color: #1890ff;
            --success-color: #52c41a;
            --warning-color: #faad14;
            --danger-color: #f5222d;
            --bg-color: #f0f2f5;
            --card-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        body {
            background-color: var(--bg-color);
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }

        .navbar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            box-shadow: var(--card-shadow);
        }

        .navbar-brand {
            font-weight: 600;
            font-size: 1.25rem;
        }

        .main-container {
            padding: 20px 0;
        }

        .config-card {
            background: white;
            border-radius: 8px;
            box-shadow: var(--card-shadow);
            margin-bottom: 20px;
            transition: all 0.3s ease;
        }

        .config-card:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }

        .config-card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 20px;
            border-radius: 8px 8px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .config-card-header h5 {
            margin: 0;
            font-weight: 600;
        }

        .config-card-body {
            padding: 20px;
        }

        .module-item {
            border: 1px solid #e8e8e8;
            border-radius: 6px;
            padding: 15px;
            margin-bottom: 15px;
            background: #fafafa;
            transition: all 0.2s ease;
            cursor: pointer;
        }

        .module-item:hover {
            border-color: var(--primary-color);
            background: #f0f7ff;
        }

        .module-item.active {
            border-color: var(--primary-color);
            background: #e6f7ff;
            box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
        }

        .module-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .module-title {
            font-weight: 600;
            color: #333;
            font-size: 1.05rem;
        }

        .badge-custom {
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 0.85rem;
        }

        .form-label {
            font-weight: 500;
            color: #555;
            margin-bottom: 8px;
        }

        .form-control:focus,
        .form-select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(24, 144, 255, 0.25);
        }

        .btn-action {
            margin-right: 8px;
        }

        .filter-group {
            background: #f9f9f9;
            border: 1px solid #e8e8e8;
            border-radius: 6px;
            padding: 15px;
            margin-bottom: 10px;
        }

        .filter-group-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            padding-bottom: 10px;
            border-bottom: 1px solid #e0e0e0;
        }

        .filter-group-title {
            font-weight: 600;
            color: #333;
        }

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #999;
        }

        .empty-state i {
            font-size: 3rem;
            margin-bottom: 15px;
            opacity: 0.5;
        }

        .data-source-card {
            border: 2px solid #e8e8e8;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .data-source-card:hover {
            border-color: var(--primary-color);
            background: #f0f7ff;
        }

        .data-source-card.selected {
            border-color: var(--primary-color);
            background: #e6f7ff;
        }

        .data-source-icon {
            font-size: 2rem;
            margin-bottom: 10px;
            color: var(--primary-color);
        }

        .help-text {
            font-size: 0.85rem;
            color: #999;
            margin-top: 5px;
        }

        .icon-btn {
            border: none;
            background: transparent;
            padding: 4px 8px;
            border-radius: 4px;
            transition: all 0.2s ease;
        }

        .icon-btn:hover {
            background: rgba(0,0,0,0.05);
        }

        .icon-btn.danger:hover {
            background: rgba(245, 34, 45, 0.1);
            color: var(--danger-color);
        }

        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin-bottom: 30px;
            padding: 0 20px;
        }

        .step {
            flex: 1;
            text-align: center;
            position: relative;
        }

        .step-number {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #e8e8e8;
            color: #999;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 10px;
            font-weight: 600;
        }

        .step.active .step-number {
            background: var(--primary-color);
            color: white;
        }

        .step.completed .step-number {
            background: var(--success-color);
            color: white;
        }

        .step-title {
            font-size: 0.9rem;
            color: #666;
        }

        .step.active .step-title {
            color: var(--primary-color);
            font-weight: 600;
        }

        .relation-hint {
            background: #fff7e6;
            border-left: 4px solid var(--warning-color);
            padding: 12px;
            border-radius: 4px;
            margin-bottom: 15px;
            font-size: 0.9rem;
        }

        .preview-panel {
            background: #f9f9f9;
            border-radius: 6px;
            padding: 15px;
            margin-top: 15px;
            border-left: 4px solid var(--primary-color);
        }

        .preview-title {
            font-weight: 600;
            color: #333;
            margin-bottom: 10px;
        }

        .code-preview {
            background: #282c34;
            color: #abb2bf;
            padding: 15px;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
            font-size: 0.85rem;
            overflow-x: auto;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-dark">
        <div class="container-fluid">
            <span class="navbar-brand">
                <i class="bi bi-speedometer2 me-2"></i>
                驾驶舱数据配置管理
            </span>
            <div>
                <button class="btn btn-light btn-sm me-2" onclick="previewConfig()">
                    <i class="bi bi-eye me-1"></i>预览配置
                </button>
                <button class="btn btn-light btn-sm me-2" onclick="saveConfig()">
                    <i class="bi bi-save me-1"></i>保存配置
                </button>
                <button class="btn btn-light btn-sm" onclick="resetConfig()">
                    <i class="bi bi-arrow-counterclockwise me-1"></i>重置
                </button>
            </div>
        </div>
    </nav>

    <!-- 主容器 -->
    <div class="container-fluid main-container">
        <div class="row">
            <!-- 左侧：模块列表 -->
            <div class="col-md-3">
                <div class="config-card">
                    <div class="config-card-header">
                        <h5><i class="bi bi-list-ul me-2"></i>数据模块</h5>
                        <button class="btn btn-sm btn-light" onclick="addModule()" title="添加模块">
                            <i class="bi bi-plus-lg"></i>
                        </button>
                    </div>
                    <div class="config-card-body">
                        <div id="moduleList">
                            <!-- 模块列表将通过JavaScript动态生成 -->
                        </div>
                        <div class="empty-state" id="emptyModuleState" style="display: none;">
                            <i class="bi bi-inbox"></i>
                            <p>暂无数据模块<br>点击上方 + 按钮添加</p>
                        </div>
                    </div>
                </div>

                <!-- 快速操作 -->
                <div class="config-card">
                    <div class="config-card-header">
                        <h5><i class="bi bi-lightning-charge me-2"></i>快速操作</h5>
                    </div>
                    <div class="config-card-body">
                        <button class="btn btn-outline-primary w-100 mb-2" onclick="importTemplate()">
                            <i class="bi bi-download me-1"></i>导入模板
                        </button>
                        <button class="btn btn-outline-success w-100 mb-2" onclick="exportConfig()">
                            <i class="bi bi-upload me-1"></i>导出配置
                        </button>
                    </div>
                </div>
            </div>

            <!-- 右侧：配置详情 -->
            <div class="col-md-9">
                <div id="configDetail" style="display: none;">
                    <!-- 步骤指示器 -->
                    <div class="step-indicator">
                        <div class="step active" id="step1">
                            <div class="step-number">1</div>
                            <div class="step-title">基本信息</div>
                        </div>
                        <div class="step" id="step2">
                            <div class="step-number">2</div>
                            <div class="step-title">数据来源</div>
                        </div>
                        <div class="step" id="step3">
                            <div class="step-number">3</div>
                            <div class="step-title">筛选条件</div>
                        </div>
                        <div class="step" id="step4">
                            <div class="step-number">4</div>
                            <div class="step-title">统计方式</div>
                        </div>
                    </div>

                    <!-- 第一步：基本信息 -->
                    <div class="config-card" id="step1Content">
                        <div class="config-card-header">
                            <h5><i class="bi bi-info-circle me-2"></i>第一步：基本信息</h5>
                        </div>
                        <div class="config-card-body">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">模块名称 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="moduleName" placeholder="例如：校友总数统计" onchange="updateStep(1)">
                                    <div class="help-text">这个模块在驾驶舱页面显示的标题</div>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">数字小数点位数</label>
                                    <input type="number" class="form-control" id="decimalPlaces" placeholder="例如：0、1、2" value="0" min="0" max="10" onchange="updateStep(1)">
                                    <div class="help-text">设置数字显示的小数点位数，0表示不显示小数</div>
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">模块说明</label>
                                    <textarea class="form-control" id="moduleDescription" rows="2" placeholder="简单描述这个模块要统计什么内容"></textarea>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 第二步：数据来源 -->
                    <div class="config-card" id="step2Content">
                        <div class="config-card-header">
                            <h5><i class="bi bi-database me-2"></i>第二步：选择数据来源</h5>
                        </div>
                        <div class="config-card-body">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="data-source-card" onclick="selectDataSource('user')" id="sourceUser">
                                        <div class="text-center">
                                            <i class="bi bi-people data-source-icon"></i>
                                            <h6>用户数据</h6>
                                            <p class="text-muted small mb-0">统计用户相关信息</p>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="data-source-card" onclick="selectDataSource('sign')" id="sourceSign">
                                        <div class="text-center">
                                            <i class="bi bi-clipboard-check data-source-icon"></i>
                                            <h6>报名数据</h6>
                                            <p class="text-muted small mb-0">统计课程报名信息</p>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="data-source-card" onclick="selectDataSource('content')" id="sourceContent">
                                        <div class="text-center">
                                            <i class="bi bi-calendar-event data-source-icon"></i>
                                            <h6>开课数据</h6>
                                            <p class="text-muted small mb-0">统计课程开课信息</p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 关联数据源提示 -->
                            <div id="relationHint" style="display: none;" class="relation-hint">
                                <i class="bi bi-info-circle me-2"></i>
                                <strong>提示：</strong>您选择了<span id="relationSourceName"></span>，可以同时关联其他数据源进行统计。
                                <div class="mt-2">
                                    <label class="form-check-label">
                                        <input type="checkbox" class="form-check-input" id="linkWithUser" onchange="updateRelation()">
                                        关联用户数据（通过报名记录关联）
                                    </label>
                                    <br>
                                    <label class="form-check-label">
                                        <input type="checkbox" class="form-check-input" id="linkWithSign" onchange="updateRelation()">
                                        关联报名数据（通过课程关联）
                                    </label>
                                    <br>
                                    <label class="form-check-label">
                                        <input type="checkbox" class="form-check-input" id="linkWithContent" onchange="updateRelation()">
                                        关联开课数据（通过课程关联）
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 第三步：筛选条件 -->
                    <div class="config-card" id="step3Content">
                        <div class="config-card-header">
                            <h5><i class="bi bi-funnel me-2"></i>第三步：设置筛选条件</h5>
                            <button class="btn btn-sm btn-light" onclick="addFilter()">
                                <i class="bi bi-plus-lg me-1"></i>添加条件
                            </button>
                        </div>
                        <div class="config-card-body">
                            <!-- 关联数据源提示 -->
                            <div id="filterRelationHint" class="relation-hint" style="display: none;">
                                <i class="bi bi-info-circle me-2"></i>
                                <strong>提示：</strong>您已关联了其他数据源，可以在筛选条件中选择不同数据源的字段进行筛选。
                                <div class="mt-2">
                                    <span class="badge bg-primary me-2" id="mainDataSourceBadge"></span>
                                    <span class="badge bg-success me-2" id="relationDataSourceBadge" style="display: none;"></span>
                                </div>
                            </div>
                            
                            <div id="filterList">
                                <!-- 筛选条件列表将通过JavaScript动态生成 -->
                            </div>
                            <div class="empty-state" id="emptyFilterState">
                                <i class="bi bi-funnel"></i>
                                <p>暂无筛选条件<br>点击上方"添加条件"按钮添加</p>
                                <p class="small text-muted mt-2">如果不添加条件，将统计所有数据</p>
                            </div>
                        </div>
                    </div>

                    <!-- 第四步：统计方式 -->
                    <div class="config-card" id="step4Content">
                        <div class="config-card-header">
                            <h5><i class="bi bi-calculator me-2"></i>第四步：设置统计方式</h5>
                        </div>
                        <div class="config-card-body">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">统计什么？ <span class="text-danger">*</span></label>
                                    <select class="form-select" id="statisticWhat" onchange="updateStatisticFields()">
                                        <option value="count">统计数量（有多少条记录）</option>
                                        <option value="count_distinct">统计去重数量（有多少个不同的）</option>
                                        <option value="sum">求和（数值相加）</option>
                                        <option value="avg">平均值</option>
                                        <option value="max">最大值</option>
                                        <option value="min">最小值</option>
                                    </select>
                                </div>
                                <div class="col-md-6 mb-3" id="statisticFieldContainer" style="display: none;">
                                    <label class="form-label">统计字段</label>
                                    <select class="form-select" id="statisticField">
                                        <option value="">请选择字段</option>
                                    </select>
                                    <div class="help-text">选择要统计的具体字段</div>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">按什么分组？</label>
                                    <select class="form-select" id="groupByField">
                                        <option value="">不分组（显示一个总数）</option>
                                    </select>
                                    <div class="help-text">如果选择分组，会按这个字段分组统计</div>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">排序方式</label>
                                    <select class="form-select" id="orderDirection">
                                        <option value="DESC">从大到小</option>
                                        <option value="ASC">从小到大</option>
                                    </select>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">最多显示多少条？</label>
                                    <input type="number" class="form-control" id="limitCount" value="10" min="0">
                                    <div class="help-text">0表示不限制，显示所有</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 配置预览 -->
                    <div class="config-card">
                        <div class="config-card-header">
                            <h5><i class="bi bi-code-square me-2"></i>配置预览</h5>
                        </div>
                        <div class="config-card-body">
                            <div class="preview-panel">
                                <div class="preview-title">配置信息</div>
                                <div class="code-preview" id="configPreview">
                                    {/* 配置JSON将通过JavaScript生成 */}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 空状态 -->
                <div id="emptyDetailState" class="text-center" style="padding: 100px 20px;">
                    <i class="bi bi-cursor" style="font-size: 4rem; color: #ccc;"></i>
                    <h4 class="mt-3 text-muted">请选择一个数据模块进行配置</h4>
                    <p class="text-muted">或点击左侧"添加模块"按钮创建新模块</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
    
    <!-- 自定义JavaScript -->
    <script>
        // 全局变量
        let modules = [];
        let currentModuleIndex = -1;
        let filterCounter = 0;
        let currentDataSource = '';

        // 字段定义
        const fields = {
            user: [
                { value: 'name', label: '姓名' },
                { value: 'mobile', label: '手机号' },
                { value: 'company_name', label: '公司名称' },
                { value: 'company_area', label: '公司区域' },
                { value: 'company_type', label: '公司类型' },
                { value: 'company_industry', label: '公司行业' },
                { value: 'is_yuanhe', label: '是否元禾投资' },
                { value: 'is_schoolmate', label: '是否校友' },
                { value: 'is_vip', label: '是否VIP' },
                { value: 'sex', label: '性别' },
                { value: 'education', label: '学历' },
                { value: 'created_at', label: '注册时间' },
                { value: 'updated_at', label: '更新时间' }
            ],
            sign: [
                { value: 'status', label: '报名状态' },
                { value: 'fee_status', label: '缴费状态' },
                { value: 'user_id', label: '用户ID' },
                { value: 'course_id', label: '课程ID' },
                { value: 'fee', label: '费用金额' },
                { value: 'created_at', label: '报名时间' },
                { value: 'updated_at', label: '更新时间' },
                { value: 'remark', label: '备注' }
            ],
            content: [
                { value: 'start_date', label: '开始日期' },
                { value: 'end_date', label: '结束日期' },
                { value: 'course_id', label: '课程ID' },
                { value: 'teacher_id', label: '老师ID' },
                { value: 'location', label: '上课地点' },
                { value: 'address', label: '详细地址' },
                { value: 'max_students', label: '最大人数' },
                { value: 'created_at', label: '创建时间' },
                { value: 'updated_at', label: '更新时间' }
            ]
        };

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadModules();
            updateModuleList();
        });

        // 加载模块数据
        function loadModules() {
            const saved = localStorage.getItem('dashboard_modules');
            if (saved) {
                modules = JSON.parse(saved);
            } else {
                modules = [
                    {
                        id: 1,
                        name: '校友总数',
                        decimalPlaces: 0,
                        dataSource: 'user',
                        relations: [],
                        filters: [],
                        statistic: { type: 'count', field: '', groupBy: '', orderDir: 'DESC', limit: 0 }
                    }
                ];
            }
        }

        // 保存模块数据
        function saveModules() {
            localStorage.setItem('dashboard_modules', JSON.stringify(modules));
        }

        // 更新模块列表显示
        function updateModuleList() {
            const moduleList = document.getElementById('moduleList');
            const emptyState = document.getElementById('emptyModuleState');
            
            if (modules.length === 0) {
                moduleList.innerHTML = '';
                emptyState.style.display = 'block';
                return;
            }

            emptyState.style.display = 'none';
            moduleList.innerHTML = modules.map((module, index) => {
                const dataSourceNames = { user: '用户', sign: '报名', content: '开课' };
                return `
                    <div class="module-item ${index === currentModuleIndex ? 'active' : ''}" onclick="selectModule(${index})">
                        <div class="module-header">
                            <div>
                                <span class="module-title">${module.name}</span>
                            </div>
                            <div>
                                <span class="badge bg-primary badge-custom">${dataSourceNames[module.dataSource] || '未设置'}</span>
                            </div>
                        </div>
                        <div class="text-muted small">
                            <i class="bi bi-calculator me-1"></i>${getStatisticTypeName(module.statistic?.type || 'count')}
                        </div>
                    </div>
                `;
            }).join('');
        }

        function getStatisticTypeName(type) {
            const names = {
                'count': '统计数量',
                'count_distinct': '去重统计',
                'sum': '求和',
                'avg': '平均值',
                'max': '最大值',
                'min': '最小值'
            };
            return names[type] || type;
        }

        // 选择模块
        function selectModule(index) {
            currentModuleIndex = index;
            updateModuleList();
            loadModuleDetail(modules[index]);
            document.getElementById('configDetail').style.display = 'block';
            document.getElementById('emptyDetailState').style.display = 'none';
            updateStep(1);
        }

        // 加载模块详情
        function loadModuleDetail(module) {
            document.getElementById('moduleName').value = module.name || '';
            document.getElementById('decimalPlaces').value = module.decimalPlaces !== undefined ? module.decimalPlaces : 0;
            document.getElementById('moduleDescription').value = module.description || '';
            
            // 数据源
            currentDataSource = module.dataSource || '';
            updateDataSourceSelection();
            updateRelationHint();
            
            // 加载关联关系
            const relations = module.relations || [];
            document.getElementById('linkWithUser').checked = relations.includes('user');
            document.getElementById('linkWithSign').checked = relations.includes('sign');
            document.getElementById('linkWithContent').checked = relations.includes('content');
            
            // 统计配置
            document.getElementById('statisticWhat').value = module.statistic?.type || 'count';
            document.getElementById('statisticField').value = module.statistic?.field || '';
            document.getElementById('groupByField').value = module.statistic?.groupBy || '';
            document.getElementById('orderDirection').value = module.statistic?.orderDir || 'DESC';
            document.getElementById('limitCount').value = module.statistic?.limit || 10;
            
            // 加载筛选条件（需要在关联关系加载后）
            loadFilters(module.filters || []);
            
            // 更新字段选项
            updateStatisticFields();
            updateGroupByFields();
            updatePreview();
        }

        // 选择数据源
        function selectDataSource(source) {
            currentDataSource = source;
            updateDataSourceSelection();
            updateStatisticFields();
            updateGroupByFields();
            updateRelationHint();
            
            // 如果已经选择了模块，保存数据源并更新筛选条件
            if (currentModuleIndex >= 0) {
                modules[currentModuleIndex].dataSource = source;
                // 清除关联关系（因为数据源变了）
                modules[currentModuleIndex].relations = [];
                document.getElementById('linkWithUser').checked = false;
                document.getElementById('linkWithSign').checked = false;
                document.getElementById('linkWithContent').checked = false;
                // 重新加载筛选条件以更新字段选项
                loadFilters(modules[currentModuleIndex].filters || []);
            }
            
            updatePreview();
        }

        function updateDataSourceSelection() {
            ['user', 'sign', 'content'].forEach(s => {
                const card = document.getElementById('source' + s.charAt(0).toUpperCase() + s.slice(1));
                if (card) {
                    card.classList.remove('selected');
                    if (s === currentDataSource) {
                        card.classList.add('selected');
                    }
                }
            });
        }

        function updateRelationHint() {
            const hint = document.getElementById('relationHint');
            const sourceNames = { user: '用户数据', sign: '报名数据', content: '开课数据' };
            
            if (currentDataSource) {
                hint.style.display = 'block';
                document.getElementById('relationSourceName').textContent = sourceNames[currentDataSource];
                
                // 根据当前数据源显示可关联的选项
                document.getElementById('linkWithUser').disabled = currentDataSource === 'user';
                document.getElementById('linkWithSign').disabled = currentDataSource === 'sign';
                document.getElementById('linkWithContent').disabled = currentDataSource === 'content';
            } else {
                hint.style.display = 'none';
            }
        }

        function updateRelation() {
            // 保存关联关系到模块
            if (currentModuleIndex >= 0) {
                const module = modules[currentModuleIndex];
                module.relations = [];
                if (document.getElementById('linkWithUser').checked) module.relations.push('user');
                if (document.getElementById('linkWithSign').checked) module.relations.push('sign');
                if (document.getElementById('linkWithContent').checked) module.relations.push('content');
                saveModules();
            }
            
            // 更新筛选条件的关联提示和字段选项
            updateFilterRelationHint();
            // 重新加载筛选条件以更新字段选项
            if (currentModuleIndex >= 0) {
                loadFilters(modules[currentModuleIndex].filters || []);
            }
            updatePreview();
        }

        // 更新统计字段选项
        function updateStatisticFields() {
            const container = document.getElementById('statisticFieldContainer');
            const select = document.getElementById('statisticField');
            const statisticType = document.getElementById('statisticWhat').value;
            
            if (statisticType === 'count') {
                container.style.display = 'none';
            } else {
                container.style.display = 'block';
                select.innerHTML = '<option value="">请选择字段</option>';
                
                if (currentDataSource && fields[currentDataSource]) {
                    fields[currentDataSource].forEach(field => {
                        select.innerHTML += `<option value="${field.value}">${field.label}</option>`;
                    });
                }
            }
            updatePreview();
        }

        // 更新分组字段选项
        function updateGroupByFields() {
            const select = document.getElementById('groupByField');
            select.innerHTML = '<option value="">不分组（显示一个总数）</option>';
            
            if (currentDataSource && fields[currentDataSource]) {
                fields[currentDataSource].forEach(field => {
                    select.innerHTML += `<option value="${field.value}">按 ${field.label} 分组</option>`;
                });
            }
        }

        // 加载筛选条件
        function loadFilters(filters) {
            const filterList = document.getElementById('filterList');
            const emptyState = document.getElementById('emptyFilterState');
            
            // 更新关联数据源提示
            updateFilterRelationHint();
            
            if (filters.length === 0) {
                filterList.innerHTML = '';
                emptyState.style.display = 'block';
                return;
            }

            emptyState.style.display = 'none';
            filterCounter = Math.max(...filters.map(f => f.id || 0), 0);
            filterList.innerHTML = filters.map((filter, index) => createFilterHTML(filter, index)).join('');
            
            // 初始化字段提示
            filterList.querySelectorAll('.filter-field').forEach(select => {
                updateFilterFieldSource(select);
            });
        }

        // 更新筛选条件的关联数据源提示
        function updateFilterRelationHint() {
            const hint = document.getElementById('filterRelationHint');
            const mainBadge = document.getElementById('mainDataSourceBadge');
            const relationBadge = document.getElementById('relationDataSourceBadge');
            
            if (!hint) return;
            
            const dataSourceNames = { user: '用户', sign: '报名', content: '开课' };
            
            if (currentDataSource) {
                mainBadge.textContent = `主数据源：${dataSourceNames[currentDataSource]}`;
                
                // 获取关联关系（从模块或checkbox状态）
                let relations = [];
                if (currentModuleIndex >= 0 && modules[currentModuleIndex].relations) {
                    relations = modules[currentModuleIndex].relations;
                } else {
                    // 如果模块还没保存，从checkbox状态获取
                    if (document.getElementById('linkWithUser') && document.getElementById('linkWithUser').checked) relations.push('user');
                    if (document.getElementById('linkWithSign') && document.getElementById('linkWithSign').checked) relations.push('sign');
                    if (document.getElementById('linkWithContent') && document.getElementById('linkWithContent').checked) relations.push('content');
                }
                
                if (relations.length > 0) {
                    hint.style.display = 'block';
                    const relationNames = relations.map(r => dataSourceNames[r]).join('、');
                    relationBadge.textContent = `关联数据源：${relationNames}`;
                    relationBadge.style.display = 'inline-block';
                } else {
                    hint.style.display = 'none';
                    relationBadge.style.display = 'none';
                }
            } else {
                hint.style.display = 'none';
            }
        }

        // 获取所有可用字段（包括关联数据源）
        function getAllAvailableFields() {
            const allFields = [];
            const dataSourceNames = { user: '用户', sign: '报名', content: '开课' };
            
            // 主数据源字段
            if (currentDataSource && fields[currentDataSource]) {
                fields[currentDataSource].forEach(field => {
                    allFields.push({
                        ...field,
                        source: currentDataSource,
                        sourceLabel: dataSourceNames[currentDataSource],
                        displayLabel: `[${dataSourceNames[currentDataSource]}] ${field.label}`
                    });
                });
            }
            
            // 关联数据源字段 - 从当前模块或checkbox状态获取
            let relations = [];
            if (currentModuleIndex >= 0 && modules[currentModuleIndex].relations) {
                relations = modules[currentModuleIndex].relations;
            } else {
                // 如果模块还没保存，从checkbox状态获取
                if (document.getElementById('linkWithUser').checked) relations.push('user');
                if (document.getElementById('linkWithSign').checked) relations.push('sign');
                if (document.getElementById('linkWithContent').checked) relations.push('content');
            }
            
            relations.forEach(relation => {
                if (fields[relation] && relation !== currentDataSource) {
                    fields[relation].forEach(field => {
                        allFields.push({
                            ...field,
                            source: relation,
                            sourceLabel: dataSourceNames[relation],
                            displayLabel: `[${dataSourceNames[relation]}] ${field.label}`
                        });
                    });
                }
            });
            
            return allFields;
        }

        // 创建筛选条件HTML
        function createFilterHTML(filter, index) {
            const allFields = getAllAvailableFields();
            const fieldOptions = allFields.map(f => 
                `<option value="${f.source}.${f.value}" ${filter.field === `${f.source}.${f.value}` || filter.field === f.value ? 'selected' : ''} data-source="${f.source}">${f.displayLabel}</option>`
            ).join('');
            
            return `
                <div class="filter-group" data-filter-id="${filter.id || index}">
                    <div class="filter-group-header">
                        <span class="filter-group-title">条件 ${index + 1}</span>
                        <button class="icon-btn" onclick="removeFilter(${filter.id || index})" title="删除">
                            <i class="bi bi-trash text-danger"></i>
                        </button>
                    </div>
                    <div class="row">
                        <div class="col-md-3 mb-2">
                            <label class="form-label">数据源和字段</label>
                            <select class="form-select filter-field" onchange="updateFilterFieldSource(this)">
                                <option value="">请选择字段</option>
                                ${fieldOptions}
                            </select>
                            <div class="help-text small mt-1" id="fieldSourceHint_${filter.id || index}"></div>
                        </div>
                        <div class="col-md-2 mb-2">
                            <label class="form-label">条件</label>
                            <select class="form-select filter-operator">
                                <option value="=" ${filter.operator === '=' ? 'selected' : ''}>=</option>
                                <option value="!=" ${filter.operator === '!=' ? 'selected' : ''}>不等于</option>
                                <option value=">" ${filter.operator === '>' ? 'selected' : ''}>大于</option>
                                <option value=">=" ${filter.operator === '>=' ? 'selected' : ''}>大于等于</option>
                                <option value="<" ${filter.operator === '<' ? 'selected' : ''}>小于</option>
                                <option value="<=" ${filter.operator === '<=' ? 'selected' : ''}>小于等于</option>
                                <option value="LIKE" ${filter.operator === 'LIKE' ? 'selected' : ''}>包含</option>
                                <option value="IN" ${filter.operator === 'IN' ? 'selected' : ''}>在列表中</option>
                            </select>
                        </div>
                        <div class="col-md-4 mb-2">
                            <label class="form-label">值</label>
                            <input type="text" class="form-control filter-value" value="${filter.value || ''}" placeholder="输入条件值">
                        </div>
                        <div class="col-md-3 mb-2">
                            <label class="form-label">与下一个条件</label>
                            <select class="form-select filter-logic">
                                <option value="AND" ${filter.logic === 'AND' ? 'selected' : ''}>并且（AND）</option>
                                <option value="OR" ${filter.logic === 'OR' ? 'selected' : ''}>或者（OR）</option>
                            </select>
                        </div>
                    </div>
                </div>
            `;
        }

        // 更新筛选字段的数据源提示
        function updateFilterFieldSource(selectElement) {
            const selectedOption = selectElement.options[selectElement.selectedIndex];
            const filterId = selectElement.closest('.filter-group').dataset.filterId;
            const hintElement = document.getElementById(`fieldSourceHint_${filterId}`);
            
            if (selectedOption && selectedOption.value) {
                const source = selectedOption.dataset.source;
                const dataSourceNames = { user: '用户数据', sign: '报名数据', content: '开课数据' };
                if (hintElement) {
                    hintElement.textContent = `来源：${dataSourceNames[source] || source}`;
                    hintElement.style.color = source === currentDataSource ? '#1890ff' : '#52c41a';
                }
            } else if (hintElement) {
                hintElement.textContent = '';
            }
        }

        // 添加模块
        function addModule() {
            const newModule = {
                id: Date.now(),
                name: '新模块',
                decimalPlaces: 0,
                dataSource: '',
                relations: [],
                filters: [],
                statistic: { type: 'count', field: '', groupBy: '', orderDir: 'DESC', limit: 10 }
            };
            modules.push(newModule);
            saveModules();
            updateModuleList();
            selectModule(modules.length - 1);
        }

        // 添加筛选条件
        function addFilter() {
            if (currentModuleIndex === -1) {
                alert('请先选择一个模块');
                return;
            }
            
            if (!currentDataSource) {
                alert('请先选择数据来源');
                return;
            }
            
            // 确保关联关系已保存到模块
            if (currentModuleIndex >= 0) {
                const module = modules[currentModuleIndex];
                module.relations = [];
                if (document.getElementById('linkWithUser').checked) module.relations.push('user');
                if (document.getElementById('linkWithSign').checked) module.relations.push('sign');
                if (document.getElementById('linkWithContent').checked) module.relations.push('content');
            }
            
            filterCounter++;
            const newFilter = {
                id: filterCounter,
                field: '',
                operator: '=',
                value: '',
                logic: 'AND'
            };
            
            if (!modules[currentModuleIndex].filters) {
                modules[currentModuleIndex].filters = [];
            }
            modules[currentModuleIndex].filters.push(newFilter);
            loadFilters(modules[currentModuleIndex].filters);
            updatePreview();
        }

        // 删除筛选条件
        function removeFilter(filterId) {
            if (currentModuleIndex === -1) return;
            
            modules[currentModuleIndex].filters = modules[currentModuleIndex].filters.filter(f => (f.id || 0) !== filterId);
            loadFilters(modules[currentModuleIndex].filters);
            updatePreview();
        }

        // 更新步骤
        function updateStep(step) {
            for (let i = 1; i <= 4; i++) {
                const stepEl = document.getElementById('step' + i);
                if (i < step) {
                    stepEl.classList.remove('active');
                    stepEl.classList.add('completed');
                } else if (i === step) {
                    stepEl.classList.add('active');
                    stepEl.classList.remove('completed');
                } else {
                    stepEl.classList.remove('active', 'completed');
                }
            }
            updatePreview();
        }

        // 保存配置
        function saveConfig() {
            if (currentModuleIndex === -1) {
                alert('请先选择一个模块');
                return;
            }

            const module = modules[currentModuleIndex];
            
            // 保存基础信息
            module.name = document.getElementById('moduleName').value;
            module.decimalPlaces = parseInt(document.getElementById('decimalPlaces').value) || 0;
            module.description = document.getElementById('moduleDescription').value;
            module.dataSource = currentDataSource;
            
            // 保存关联关系
            module.relations = [];
            if (document.getElementById('linkWithUser').checked) module.relations.push('user');
            if (document.getElementById('linkWithSign').checked) module.relations.push('sign');
            if (document.getElementById('linkWithContent').checked) module.relations.push('content');
            
            // 保存统计配置
            module.statistic = {
                type: document.getElementById('statisticWhat').value,
                field: document.getElementById('statisticField').value,
                groupBy: document.getElementById('groupByField').value,
                orderDir: document.getElementById('orderDirection').value,
                limit: parseInt(document.getElementById('limitCount').value) || 0
            };
            
            // 保存筛选条件
            const filterGroups = document.querySelectorAll('.filter-group');
            module.filters = Array.from(filterGroups).map(group => {
                const fieldValue = group.querySelector('.filter-field').value;
                // 如果字段值包含点号，说明是关联数据源的字段（格式：source.field）
                // 否则是主数据源的字段
                return {
                    id: parseInt(group.dataset.filterId) || 0,
                    field: fieldValue,
                    operator: group.querySelector('.filter-operator').value,
                    value: group.querySelector('.filter-value').value,
                    logic: group.querySelector('.filter-logic').value
                };
            });
            
            saveModules();
            updateModuleList();
            updatePreview();
            
            alert('配置已保存！');
        }

        // 更新预览
        function updatePreview() {
            if (currentModuleIndex === -1) return;
            
            const module = modules[currentModuleIndex];
            const preview = document.getElementById('configPreview');
            
            // 生成友好的配置描述
            let description = `模块名称：${module.name || '未设置'}\n`;
            description += `小数点位数：${module.decimalPlaces !== undefined ? module.decimalPlaces : 0}\n`;
            description += `数据来源：${currentDataSource ? (currentDataSource === 'user' ? '用户' : currentDataSource === 'sign' ? '报名' : '开课') : '未选择'}\n`;
            description += `统计方式：${getStatisticDescription(module.statistic)}\n`;
            description += `筛选条件：${module.filters?.length || 0} 个\n`;
            
            preview.textContent = description + '\n\n完整配置JSON：\n' + JSON.stringify(module, null, 2);
        }

        function getStatisticDescription(statistic) {
            if (!statistic) return '未设置';
            const types = {
                'count': '统计数量',
                'count_distinct': '统计去重数量',
                'sum': '求和',
                'avg': '平均值',
                'max': '最大值',
                'min': '最小值'
            };
            let desc = types[statistic.type] || statistic.type;
            if (statistic.field) desc += ` (字段：${statistic.field})`;
            if (statistic.groupBy) desc += `，按 ${statistic.groupBy} 分组`;
            return desc;
        }


        // 预览配置
        function previewConfig() {
            if (currentModuleIndex === -1) {
                alert('请先选择一个模块');
                return;
            }
            updatePreview();
            alert('配置预览已更新，请查看下方"配置预览"区域');
        }

        // 重置配置
        function resetConfig() {
            if (confirm('确定要重置所有配置吗？此操作不可恢复！')) {
                localStorage.removeItem('dashboard_modules');
                modules = [];
                currentModuleIndex = -1;
                updateModuleList();
                document.getElementById('configDetail').style.display = 'none';
                document.getElementById('emptyDetailState').style.display = 'block';
                alert('配置已重置');
            }
        }

        // 导出配置
        function exportConfig() {
            const dataStr = JSON.stringify(modules, null, 2);
            const dataBlob = new Blob([dataStr], { type: 'application/json' });
            const url = URL.createObjectURL(dataBlob);
            const link = document.createElement('a');
            link.href = url;
            link.download = 'dashboard-config-' + new Date().getTime() + '.json';
            link.click();
        }

        // 导入模板
        function importTemplate() {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = 'application/json';
            input.onchange = function(e) {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        try {
                            modules = JSON.parse(e.target.result);
                            saveModules();
                            updateModuleList();
                            alert('配置导入成功！');
                        } catch (err) {
                            alert('配置文件格式错误！');
                        }
                    };
                    reader.readAsText(file);
                }
            };
            input.click();
        }

        // 监听字段变化
        ['statisticWhat', 'groupByField', 'decimalPlaces'].forEach(id => {
            const element = document.getElementById(id);
            if (element) {
                element.addEventListener('change', updatePreview);
            }
        });
    </script>
</body>
</html>
