<?php
$title='数据导入';
include __DIR__ . '/head.php';

// 检查是否有老数据库配置
$old_db_config_file = dirname(__DIR__) . '/old_db_config.php';
$old_db_config = [];
if(file_exists($old_db_config_file)){
    $old_db_config = include $old_db_config_file;
}
?>

<div class="p-4 md:p-6">
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="p-4 md:p-6 border-b border-gray-200">
            <h2 class="text-base md:text-lg font-semibold text-gray-800">
                <i class="fas fa-database mr-2 text-blue-500"></i>白菜数据导入（老系统迁移）
            </h2>
        </div>
        <div class="p-4 md:p-6">
            <div class="mb-6 p-4 bg-amber-50 border border-amber-200 rounded-lg">
                <p class="text-sm text-amber-700">
                    <i class="fas fa-exclamation-triangle mr-2"></i><strong>注意事项：</strong><br>
                    1. 导入前请先备份当前数据库<br>
                    2. 导入会覆盖已有数据（相同ID的数据会被替换）<br>
                    3. 卡密表的预存提成金额将设为0<br>
                    4. 用户表会导入余额和佣金数据<br>
                    5. 多余的字段（如价格体系等）会被忽略
                </p>
            </div>

            <!-- 数据库配置 -->
            <div class="mb-6 p-4 bg-gray-50 rounded-lg">
                <h3 class="text-sm font-semibold text-gray-700 mb-3">
                    <i class="fas fa-cog mr-2"></i>老数据库配置
                </h3>
                <form id="dbConfigForm" class="space-y-3">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm text-gray-600 mb-1">数据库地址</label>
                            <input type="text" id="db_host" value="<?php echo htmlspecialchars($old_db_config['db_host'] ?? 'localhost'); ?>" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>
                        <div>
                            <label class="block text-sm text-gray-600 mb-1">数据库端口</label>
                            <input type="text" id="db_port" value="<?php echo htmlspecialchars($old_db_config['db_port'] ?? '3306'); ?>" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>
                        <div>
                            <label class="block text-sm text-gray-600 mb-1">数据库名称</label>
                            <input type="text" id="db_name" value="<?php echo htmlspecialchars($old_db_config['db_name'] ?? ''); ?>" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>
                        <div>
                            <label class="block text-sm text-gray-600 mb-1">数据库用户</label>
                            <input type="text" id="db_user" value="<?php echo htmlspecialchars($old_db_config['db_user'] ?? ''); ?>" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>
                        <div>
                            <label class="block text-sm text-gray-600 mb-1">数据库密码</label>
                            <input type="password" id="db_pwd" value="<?php echo htmlspecialchars($old_db_config['db_pwd'] ?? ''); ?>" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>
                        <div>
                            <label class="block text-sm text-gray-600 mb-1">表前缀（老系统默认bot_）</label>
                            <input type="text" id="db_prefix" value="<?php echo htmlspecialchars($old_db_config['db_prefix'] ?? 'bot_'); ?>" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                        </div>
                    </div>
                    <div class="flex gap-2">
                        <button type="button" onclick="testConnection()" class="px-4 py-2 bg-gray-200 hover:bg-gray-300 text-gray-700 text-sm font-medium rounded-lg transition">
                            <i class="fas fa-plug mr-1"></i>测试连接
                        </button>
                        <button type="button" onclick="saveConfig()" class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white text-sm font-medium rounded-lg transition">
                            <i class="fas fa-save mr-1"></i>保存配置
                        </button>
                    </div>
                </form>
            </div>

            <!-- 导入选项 -->
            <div class="mb-6 p-4 bg-blue-50 rounded-lg">
                <h3 class="text-sm font-semibold text-gray-700 mb-3">
                    <i class="fas fa-download mr-2"></i>选择要导入的数据表
                </h3>
                <div class="space-y-2">
                    <label class="flex items-center">
                        <input type="checkbox" id="import_user" checked class="w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500">
                        <span class="ml-2 text-sm text-gray-700">用户表 (bot_user → pre_user)</span>
                    </label>
                    <label class="flex items-center">
                        <input type="checkbox" id="import_login_class" checked class="w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500">
                        <span class="ml-2 text-sm text-gray-700">登录分类表 (bot_login_class → pre_login_class)</span>
                    </label>
                    <label class="flex items-center">
                        <input type="checkbox" id="import_loginconfig" checked class="w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500">
                        <span class="ml-2 text-sm text-gray-700">登录接口配置表 (bot_loginconfig → pre_loginconfig)</span>
                    </label>
                    <label class="flex items-center">
                        <input type="checkbox" id="import_qq" checked class="w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500">
                        <span class="ml-2 text-sm text-gray-700">QQ账号表 (bot_qq → pre_qq)</span>
                    </label>
                    <label class="flex items-center">
                        <input type="checkbox" id="import_goods" checked class="w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500">
                        <span class="ml-2 text-sm text-gray-700">商品表 (bot_goods → pre_goods)</span>
                    </label>
                    <label class="flex items-center">
                        <input type="checkbox" id="import_km" class="w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500">
                        <span class="ml-2 text-sm text-gray-700">卡密表 (bot_km → pre_km) <span class="text-amber-600">预存提成将为0</span></span>
                    </label>
                </div>
            </div>

            <!-- 导入按钮 -->
            <div class="flex flex-wrap gap-3">
                <button type="button" onclick="startImport()" id="btn_import" class="px-6 py-2.5 bg-green-500 hover:bg-green-600 text-white text-sm font-medium rounded-lg transition">
                    <i class="fas fa-play mr-2"></i>开始导入
                </button>
                <button type="button" onclick="clearData()" class="px-6 py-2.5 bg-red-500 hover:bg-red-600 text-white text-sm font-medium rounded-lg transition">
                    <i class="fas fa-trash mr-2"></i>清空当前数据
                </button>
            </div>

            <!-- 进度显示 -->
            <div id="progress_area" class="mt-6 hidden">
                <div class="p-4 bg-gray-50 rounded-lg">
                    <div class="flex items-center justify-between mb-2">
                        <span class="text-sm font-medium text-gray-700" id="progress_title">准备中...</span>
                        <span class="text-sm text-gray-500" id="progress_percent">0%</span>
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-2.5">
                        <div id="progress_bar" class="bg-blue-600 h-2.5 rounded-full transition-all duration-300" style="width: 0%"></div>
                    </div>
                    <div id="progress_log" class="mt-3 text-xs text-gray-600 max-h-60 overflow-y-auto font-mono bg-white p-3 rounded border">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 确认清空弹窗 -->
<div class="modal fade" id="clearModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-red-50">
                <h5 class="modal-title text-red-600"><i class="fas fa-exclamation-triangle mr-2"></i>确认清空</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p class="text-gray-700">确定要清空当前数据库的以下表吗？此操作不可恢复！</p>
                <ul class="mt-2 text-sm text-gray-600 list-disc list-inside">
                    <li>pre_user (用户表)</li>
                    <li>pre_login_class (登录分类表)</li>
                    <li>pre_loginconfig (登录接口配置表)</li>
                    <li>pre_qq (QQ账号表)</li>
                    <li>pre_goods (商品表)</li>
                    <li>pre_km (卡密表)</li>
                </ul>
                <div class="mt-3 p-2 bg-red-50 rounded text-sm text-red-600">
                    <i class="fas fa-info-circle mr-1"></i>管理员账号（zid=1）将被保留
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="confirmClear()">确认清空</button>
            </div>
        </div>
    </div>
</div>

<script>
function showLoading() {
    document.getElementById('loadingOverlay').classList.remove('hidden');
}
function hideLoading() {
    document.getElementById('loadingOverlay').classList.add('hidden');
}
function showToast(msg, type = 'info') {
    var toastWrap = document.getElementById('toastWrap');
    var toast = document.createElement('div');
    var bgColor = type === 'success' ? 'bg-green-500' : type === 'error' ? 'bg-red-500' : 'bg-blue-500';
    toast.className = bgColor + ' text-white px-4 py-3 rounded-lg shadow-lg flex items-center gap-2 transform transition-all duration-300 translate-y-0 opacity-100';
    toast.innerHTML = '<i class="fas fa-' + (type === 'success' ? 'check-circle' : type === 'error' ? 'times-circle' : 'info-circle') + '"></i><span>' + msg + '</span>';
    toastWrap.appendChild(toast);
    setTimeout(function() {
        toast.classList.add('translate-y-2', 'opacity-0');
        setTimeout(function() { toast.remove(); }, 300);
    }, 3000);
}

function getDbConfig() {
    return {
        db_host: $('#db_host').val(),
        db_port: $('#db_port').val(),
        db_name: $('#db_name').val(),
        db_user: $('#db_user').val(),
        db_pwd: $('#db_pwd').val(),
        db_prefix: $('#db_prefix').val()
    };
}

function testConnection() {
    showLoading();
    $.ajax({
        type: 'POST',
        url: 'ajax_import.php?act=test_connection',
        data: getDbConfig(),
        dataType: 'json',
        timeout: 10000,
        success: function(data) {
            hideLoading();
            if(data.code == 1) {
                showToast('连接成功！' + data.msg, 'success');
            } else {
                showToast(data.msg, 'error');
            }
        },
        error: function(xhr, status, error) {
            hideLoading();
            if(status === 'timeout') {
                showToast('连接超时，请检查数据库地址和端口', 'error');
            } else {
                showToast('连接失败，请检查配置', 'error');
            }
        }
    });
}

function saveConfig() {
    showLoading();
    $.ajax({
        type: 'POST',
        url: 'ajax_import.php?act=save_config',
        data: getDbConfig(),
        dataType: 'json',
        success: function(data) {
            hideLoading();
            if(data.code == 1) {
                showToast('配置已保存', 'success');
            } else {
                showToast(data.msg, 'error');
            }
        },
        error: function() {
            hideLoading();
            showToast('请求失败', 'error');
        }
    });
}

function startImport() {
    var tables = [];
    if($('#import_user').is(':checked')) tables.push('user');
    if($('#import_login_class').is(':checked')) tables.push('login_class');
    if($('#import_loginconfig').is(':checked')) tables.push('loginconfig');
    if($('#import_qq').is(':checked')) tables.push('qq');
    if($('#import_goods').is(':checked')) tables.push('goods');
    if($('#import_km').is(':checked')) tables.push('km');

    if(tables.length == 0) {
        showToast('请至少选择一个表进行导入', 'error');
        return;
    }

    if(!confirm('确定要开始导入吗？导入将覆盖已有数据！')) {
        return;
    }

    $('#btn_import').prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-2"></i>导入中...');
    $('#progress_area').removeClass('hidden');
    $('#progress_log').html('');
    updateProgress(0, '准备中...');

    importTables(tables, 0);
}

var importStats = {}; // 记录每个表的导入统计

function importTables(tables, index) {
    if(index >= tables.length) {
        updateProgress(100, '导入完成！');
        var summary = [];
        for(var t in importStats) {
            summary.push(getTableLabel(t) + ': ' + importStats[t] + ' 条');
        }
        addLog('<span class="text-green-600 font-bold">[完成]</span> 所有数据导入完成！' + summary.join('，'));
        showToast('所有数据导入完成！', 'success');
        $('#btn_import').prop('disabled', false).html('<i class="fas fa-play mr-2"></i>开始导入');
        return;
    }

    var table = tables[index];
    importStats[table] = 0;

    // 先获取表总数
    $.ajax({
        type: 'POST',
        url: 'ajax_import.php?act=get_table_count',
        data: $.extend(getDbConfig(), {table: table}),
        dataType: 'json',
        success: function(data) {
            if(data.code == 1) {
                var totalCount = data.count;
                addLog('开始导入 ' + getTableLabel(table) + '，共 ' + totalCount + ' 条记录...');
                // 开始分批导入
                importTableBatch(table, 0, 5000, totalCount, tables, index);
            } else {
                addLog('<span class="text-red-600">[失败]</span> 获取 ' + getTableLabel(table) + ' 数量失败：' + data.msg);
                setTimeout(function() {
                    importTables(tables, index + 1);
                }, 500);
            }
        },
        error: function() {
            addLog('<span class="text-red-600">[错误]</span> 获取 ' + getTableLabel(table) + ' 数量请求失败');
            setTimeout(function() {
                importTables(tables, index + 1);
            }, 500);
        }
    });
}

function importTableBatch(table, offset, limit, totalCount, tables, tableIndex) {
    var progress = Math.round((tableIndex / tables.length) * 100 + (offset / totalCount) * (100 / tables.length));
    updateProgress(Math.min(progress, 99), '正在导入 ' + getTableLabel(table) + ' (' + offset + '/' + totalCount + ')...');

    $.ajax({
        type: 'POST',
        url: 'ajax_import.php?act=import_table',
        data: $.extend(getDbConfig(), {table: table, offset: offset, limit: limit}),
        dataType: 'json',
        timeout: 600000,
        success: function(data) {
            if(data.code == 1) {
                importStats[table] += data.count;
                if(data.log && data.log.length > 0) {
                    data.log.forEach(function(msg) {
                        addLog('  ' + msg);
                    });
                }

                // 检查是否还有更多数据
                if(data.offset < totalCount) {
                    // 继续下一批
                    setTimeout(function() {
                        importTableBatch(table, data.offset, limit, totalCount, tables, tableIndex);
                    }, 100);
                } else {
                    // 当前表导入完成
                    addLog('<span class="text-green-600">[完成]</span> ' + getTableLabel(table) + ' 导入完成，共 ' + importStats[table] + ' 条');
                    setTimeout(function() {
                        importTables(tables, tableIndex + 1);
                    }, 500);
                }
            } else {
                addLog('<span class="text-red-600">[失败]</span> ' + getTableLabel(table) + ' 导入失败：' + data.msg);
                setTimeout(function() {
                    importTables(tables, tableIndex + 1);
                }, 500);
            }
        },
        error: function(xhr, status, error) {
            addLog('<span class="text-red-600">[错误]</span> ' + getTableLabel(table) + ' 请求失败：' + error);
            setTimeout(function() {
                importTables(tables, tableIndex + 1);
            }, 500);
        }
    });
}

function getTableLabel(table) {
    var labels = {
        'user': '用户表',
        'login_class': '登录分类表',
        'loginconfig': '登录接口配置表',
        'qq': 'QQ账号表',
        'goods': '商品表',
        'km': '卡密表'
    };
    return labels[table] || table;
}

function updateProgress(percent, title) {
    $('#progress_bar').css('width', percent + '%');
    $('#progress_percent').text(percent + '%');
    if(title) $('#progress_title').text(title);
}

function addLog(msg) {
    var log = $('#progress_log');
    var time = new Date().toLocaleTimeString();
    log.append('<div>[' + time + '] ' + msg + '</div>');
    log.scrollTop(log[0].scrollHeight);
}

function clearData() {
    var modal = new bootstrap.Modal(document.getElementById('clearModal'));
    modal.show();
}

function confirmClear() {
    showLoading();
    $.ajax({
        type: 'POST',
        url: 'ajax_import.php?act=clear_data',
        dataType: 'json',
        success: function(data) {
            hideLoading();
            bootstrap.Modal.getInstance(document.getElementById('clearModal')).hide();
            if(data.code == 1) {
                showToast('数据已清空', 'success');
            } else {
                showToast(data.msg, 'error');
            }
        },
        error: function() {
            hideLoading();
            showToast('请求失败', 'error');
        }
    });
}
</script>
<?php include 'foot.php'; ?>
