// 加载生成配置列表
async function loadGenerateConfigs() {
    try {
        const response = await fetch('/api/config');
        const result = await response.json();
        
        if (result.success) {
            const container = document.getElementById('config-checkbox-list');
            container.innerHTML = result.data.map(c => `
                <label style="display: flex; align-items: center; gap: 8px; padding: 6px 0; cursor: pointer;">
                    <input type="checkbox" class="config-checkbox" value="${c.id}" data-name="${c.config_name}">
                    <span>${c.config_name}</span>
                </label>
            `).join('');
        }
    } catch (error) {
        console.error('加载配置失败:', error);
    }
}

// 全选/取消全选配置
function toggleSelectAllConfigs() {
    const selectAll = document.getElementById('select-all-configs');
    const checkboxes = document.querySelectorAll('.config-checkbox');
    checkboxes.forEach(cb => {
        cb.checked = selectAll.checked;
    });
}

// 设置预设时间
function setPresetTime(preset) {
    const now = new Date();
    let start, end;

    if (preset === 'yesterday') {
        end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 8, 0, 0);
        start = new Date(end.getTime() - 24 * 60 * 60 * 1000);
    } else if (preset === 'last3days') {
        end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 8, 0, 0);
        start = new Date(end.getTime() - 3 * 24 * 60 * 60 * 1000);
    } else if (preset === 'last7days') {
        end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 8, 0, 0);
        start = new Date(end.getTime() - 7 * 24 * 60 * 60 * 1000);
    }

    document.getElementById('start-time').value = formatDateTimeLocal(start);
    document.getElementById('end-time').value = formatDateTimeLocal(end);
}

// 格式化日期时间（用于输入框）
function formatDateTimeLocal(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day}T${hours}:${minutes}`;
}

// 格式化日期时间为数字格式（用于显示）
function formatDateTimeDisplay(dateTimeStr) {
    if (!dateTimeStr) return '-';
    // 如果是字符串，直接返回（已经是数字格式）
    if (typeof dateTimeStr === 'string') {
        // 如果是 ISO 格式或其他格式，转换为 YYYY-MM-DD HH:MM:SS
        const date = new Date(dateTimeStr);
        if (!isNaN(date.getTime())) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }
        return dateTimeStr;
    }
    return String(dateTimeStr);
}

// 格式化日期为数字格式（只显示日期，用于显示）
function formatDateDisplay(dateStr) {
    if (!dateStr) return '-';
    const date = new Date(dateStr);
    if (!isNaN(date.getTime())) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }
    return String(dateStr);
}

// 生成日报（支持多选）
async function generateReport() {
    const checkboxes = document.querySelectorAll('.config-checkbox:checked');
    const startTime = document.getElementById('start-time').value;
    const endTime = document.getElementById('end-time').value;

    if (checkboxes.length === 0) {
        alert('请至少选择一个配置');
        return;
    }

    if (!startTime || !endTime) {
        alert('请选择时间范围');
        return;
    }

    const resultDiv = document.getElementById('generate-result');
    resultDiv.innerHTML = '<div class="alert alert-info">正在批量生成日报，请稍候...</div>';

    let successCount = 0;
    let failCount = 0;
    let results = [];

    for (const cb of checkboxes) {
        const configId = parseInt(cb.value);
        const configName = cb.dataset.name;

        try {
            const response = await fetch('/api/report/generate', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    config_id: configId,
                    start_time: startTime.replace('T', ' ') + ':00',
                    end_time: endTime.replace('T', ' ') + ':00'
                })
            });

            const result = await response.json();
            
            if (result.success) {
                successCount++;
                results.push({ name: configName, success: true, ...result });
            } else {
                failCount++;
                results.push({ name: configName, success: false, message: result.message });
            }
        } catch (error) {
            failCount++;
            results.push({ name: configName, success: false, message: error.message });
        }
    }

    // 显示结果
    let html = '<div class="alert alert-info"><strong>生成完成</strong><br><br>';
    html += `成功：${successCount} 个，失败：${failCount} 个<br><br>`;
    
    results.forEach(r => {
        if (r.success) {
            html += `<div style="margin: 10px 0; padding: 10px; background: #f0f8ff; border-radius: 4px;">`;
            html += `<strong>✓ ${r.name}</strong><br>`;
            html += `订单数量：${r.total_orders} 条，总金额：¥${r.total_amount.toFixed(2)}<br>`;
            html += `<a href="/api/download?path=${r.file_path}" target="_blank" class="btn btn-sm btn-success" style="margin-top: 5px;">📥 下载</a>`;
            html += `</div>`;
        } else {
            html += `<div style="margin: 10px 0; padding: 10px; background: #fff0f0; border-radius: 4px;">`;
            html += `<strong>✗ ${r.name}</strong><br>`;
            html += `错误：${r.message}`;
            html += `</div>`;
        }
    });
    
    html += '</div>';
    resultDiv.innerHTML = html;
}

