// 批量编辑第三步 - 确认预览页面

let selectedShops = [];
let levelData = [];

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    loadStoredData();
    generatePreview();
    updateSummaryStats();
});

// 加载存储的数据
function loadStoredData() {
    // 加载选中的店铺
    const storedShops = sessionStorage.getItem('batchEditSelectedShops');
    if (storedShops) {
        selectedShops = JSON.parse(storedShops);
    } else {
        showNotification('未找到选中的店铺数据，请重新操作', 'error');
        setTimeout(() => {
            navigateTo('batch-edit-step1.html');
        }, 2000);
        return;
    }

    // 加载等级设置数据
    const storedLevels = sessionStorage.getItem('batchEditLevelData');
    if (storedLevels) {
        levelData = JSON.parse(storedLevels);
    } else {
        showNotification('未找到等级设置数据，请重新设置', 'error');
        setTimeout(() => {
            navigateTo('batch-edit-step2.html');
        }, 2000);
        return;
    }
}

// 生成预览表格
function generatePreview() {
    const tableBody = document.getElementById('preview-table-body');
    
    const html = selectedShops.map(shop => {
        const beforeLevels = shop.levels.join(', ');
        const afterLevels = levelData.map(level => level.level).join(', ');
        
        return `
            <tr>
                <td>
                    <div class="shop-name">${shop.name}</div>
                </td>
                <td>
                    <div class="levels-before">${beforeLevels}</div>
                </td>
                <td>
                    <div class="levels-after">${afterLevels}</div>
                    <div class="change-indicator">
                        <span class="change-arrow">→</span>
                        <span>新设置</span>
                    </div>
                </td>
                <td>
                    <div class="member-count">${shop.memberCount} 人</div>
                </td>
            </tr>
        `;
    }).join('');
    
    tableBody.innerHTML = html;
}

// 更新摘要统计
function updateSummaryStats() {
    const shopCount = selectedShops.length;
    const totalMembers = selectedShops.reduce((sum, shop) => sum + shop.memberCount, 0);
    
    document.getElementById('shop-count').textContent = shopCount;
    document.getElementById('member-count').textContent = totalMembers.toLocaleString();
}

// 上一步 - 返回修改
function previousStep() {
    navigateTo('batch-edit-step2.html');
}

// 确认提交
function confirmSubmit() {
    const shopCount = selectedShops.length;
    const totalMembers = selectedShops.reduce((sum, shop) => sum + shop.memberCount, 0);
    
    const message = `确定要为 ${shopCount} 个店铺的 ${totalMembers.toLocaleString()} 名会员应用新的等级设置吗？\n\n此操作不可撤销，请谨慎确认。`;
    
    confirmAction(message, () => {
        executeSubmit();
    });
}

// 执行提交
function executeSubmit() {
    // 隐藏操作按钮，显示进度
    document.getElementById('action-buttons').style.display = 'none';
    document.getElementById('submit-progress').style.display = 'block';
    
    simulateSubmitProgress();
}

// 模拟提交进度
function simulateSubmitProgress() {
    const progressFill = document.getElementById('progress-fill');
    const progressText = document.getElementById('progress-text');
    
    const steps = [
        { progress: 10, text: '验证店铺数据...' },
        { progress: 25, text: '备份现有设置...' },
        { progress: 40, text: '应用等级设置...' },
        { progress: 60, text: '更新会员等级...' },
        { progress: 80, text: '发送通知消息...' },
        { progress: 95, text: '清理缓存数据...' },
        { progress: 100, text: '操作完成！' }
    ];
    
    let currentStep = 0;
    
    const updateProgress = () => {
        if (currentStep < steps.length) {
            const step = steps[currentStep];
            progressFill.style.width = step.progress + '%';
            progressText.textContent = step.text;
            
            currentStep++;
            
            // 模拟不同步骤的处理时间
            const delay = currentStep === steps.length ? 1000 : Math.random() * 1000 + 500;
            setTimeout(updateProgress, delay);
        } else {
            // 提交完成
            onSubmitComplete();
        }
    };
    
    updateProgress();
}

// 提交完成处理
function onSubmitComplete() {
    // 清理存储的数据
    sessionStorage.removeItem('batchEditSelectedShops');
    sessionStorage.removeItem('batchEditLevelData');
    
    // 显示成功消息
    const shopCount = selectedShops.length;
    const totalMembers = selectedShops.reduce((sum, shop) => sum + shop.memberCount, 0);
    
    showNotification(
        `批量设置成功！已为 ${shopCount} 个店铺的 ${totalMembers.toLocaleString()} 名会员应用新的等级设置。`, 
        'success',
        5000
    );
    
    // 延迟跳转回等级设置主页
    setTimeout(() => {
        navigateTo('level-settings.html');
    }, 3000);
}

// 生成操作日志（用于后续可能的撤销功能）
function generateOperationLog() {
    const operationLog = {
        timestamp: new Date().toISOString(),
        operation: 'batch_level_edit',
        affectedShops: selectedShops.map(shop => ({
            shopId: shop.id,
            shopName: shop.name,
            beforeLevels: shop.levels,
            afterLevels: levelData.map(level => level.level),
            memberCount: shop.memberCount
        })),
        newLevelSettings: levelData,
        summary: {
            shopCount: selectedShops.length,
            totalMembers: selectedShops.reduce((sum, shop) => sum + shop.memberCount, 0)
        }
    };
    
    // 在实际项目中，这里会将日志发送到服务器
    console.log('操作日志：', operationLog);
    
    return operationLog;
}

// 导出函数到全局
window.previousStep = previousStep;
window.confirmSubmit = confirmSubmit;