<?php
require_once __DIR__ . '/../MPHX/common.php';

// 导入调试日志函数（已禁用）
if (!function_exists('import_debug_log')) {
    function import_debug_log($message) {
        // 调试日志已禁用
    }
}

// 增加PHP执行时间，防止导入大文件时超时
set_time_limit(600); // 10分钟
ini_set('max_execution_time', 600);

// 设置错误处理，确保AJAX请求返回JSON格式
set_error_handler(function($errno, $errstr, $errfile, $errline) {
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) || ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']))) {
        header('Content-Type: application/json');
        exit(json_encode(array('code' => '服务器错误: ' . $errstr . ' (文件: ' . basename($errfile) . ', 行: ' . $errline . ')')));
    }
    return false;
});

set_exception_handler(function($e) {
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) || ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']))) {
        header('Content-Type: application/json');
        exit(json_encode(array('code' => '服务器异常: ' . $e->getMessage())));
    }
});

/**
 * 下载外部系统文件（带重试机制）
 * @param string $url 文件下载URL
 * @param string $save_dir 保存目录
 * @param string $original_filename 原始文件名
 * @param int $max_retries 最大重试次数
 * @return string|false 新文件名或false
 */
function downloadExternalFile($url, $save_dir, $original_filename, $max_retries = 3) {
    // 生成新文件名
    $file_extension = pathinfo($original_filename, PATHINFO_EXTENSION);
    if (empty($file_extension)) {
        $file_extension = 'bin';
    }
    $new_filename = uniqid() . '_' . time() . '.' . strtolower($file_extension);
    $save_path = $save_dir . $new_filename;

    // 获取文件大小（HEAD请求）
    $expected_size = 0;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    
    $header = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    // 从header中提取Content-Length
    if (preg_match('/Content-Length:\s*(\d+)/i', $header, $matches)) {
        $expected_size = intval($matches[1]);
    }
    curl_close($ch);
    
    if ($http_code != 200) {
        return false;
    }

    // 使用文件流下载大文件，带断点续传和重试
    $retry_count = 0;
    $resume_from = 0;
    
    while ($retry_count < $max_retries) {
        $fp = fopen($save_path, $retry_count == 0 ? 'w+' : 'a+');
        if (!$fp) {
            return false;
        }
        
        // 获取已下载大小
        if ($retry_count > 0) {
            $resume_from = filesize($save_path);
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 300);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HEADER, false);
        
        // 断点续传
        if ($resume_from > 0) {
            curl_setopt($ch, CURLOPT_RANGE, "{$resume_from}-");
        }
        
        // 保持连接活跃
        curl_setopt($ch, CURLOPT_TCP_KEEPALIVE, 1);
        curl_setopt($ch, CURLOPT_TCP_KEEPIDLE, 120);
        curl_setopt($ch, CURLOPT_TCP_KEEPINTVL, 60);

        $success = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curl_error = curl_error($ch);
        curl_close($ch);
        fclose($fp);

        // 检查下载结果
        if (file_exists($save_path)) {
            $downloaded_size = filesize($save_path);
            
            // 如果文件下载完整（有预期大小且匹配，或者没有预期大小但文件非空）
            if (($expected_size > 0 && $downloaded_size >= $expected_size) || 
                ($expected_size == 0 && $downloaded_size > 0)) {
                return $new_filename;
            }
            
            // 如果下载了部分数据，尝试继续
            if ($downloaded_size > $resume_from) {
                $retry_count++;
                sleep(1); // 等待1秒后重试
                continue;
            }
        }
        
        // 如果没有任何进展，重试
        if (!$success && $curl_error) {
        }
        
        $retry_count++;
        if ($retry_count < $max_retries) {
            sleep(1);
        }
    }

    // 最终检查
    if (file_exists($save_path) && filesize($save_path) > 0) {
        return $new_filename;
    }

    @unlink($save_path);
    return false;
}

// 检查是否为AJAX请求
$is_ajax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';

if (!is_admin_login()) {
    if ($is_ajax || ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']))) {
        header('Content-Type: application/json');
        exit(json_encode(array('code' => '请先登录')));
    }
    header('Location: /admin/login.php');
    exit;
}

$gn = isset($_GET['gn']) ? $_GET['gn'] : '';

// 处理AJAX请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    $action = $_POST['action'];
    
    switch ($action) {
        case 'add':
            $name = daddslashes(trim($_POST['name']));
            if (empty($name)) {
                exit(json_encode(array('code' => '密钥名称不能为空')));
            }
            // 生成随机API密钥
            $api_key = bin2hex(random_bytes(32));
            $DB->query("INSERT INTO `system_api_keys` (`api_key`, `name`) VALUES ('{$api_key}', '{$name}')");
            logjl(is_admin_login(), 'API密钥管理', '添加API密钥: ' . $name, true);
            exit(json_encode(array('code' => '添加成功', 'api_key' => $api_key)));
            break;
            
        case 'delete':
            $id = intval($_POST['id']);
            $DB->query("DELETE FROM `system_api_keys` WHERE `id`={$id}");
            logjl(is_admin_login(), 'API密钥管理', '删除API密钥 ID: ' . $id, true);
            exit(json_encode(array('code' => '删除成功')));
            break;
            
        case 'toggle':
            $id = intval($_POST['id']);
            $key_info = $DB->get_row("SELECT * FROM `system_api_keys` WHERE `id`={$id}");
            if ($key_info) {
                $new_status = $key_info['status'] == 1 ? 0 : 1;
                $DB->query("UPDATE `system_api_keys` SET `status`={$new_status} WHERE `id`={$id}");
                logjl(is_admin_login(), 'API密钥管理', '切换API密钥状态 ID: ' . $id, true);
                exit(json_encode(array('code' => '操作成功', 'status' => $new_status)));
            }
            exit(json_encode(array('code' => '密钥不存在')));
            break;
            
        case 'fetch_programs':
            // 从外部系统获取程序列表
            $api_url = trim($_POST['api_url']);
            $api_key = trim($_POST['api_key']);

            if (empty($api_url) || empty($api_key)) {
                exit(json_encode(array('code' => 'API地址和密钥不能为空')));
            }

            // 智能处理URL：如果用户输入了完整路径，提取基础URL
            if (strpos($api_url, '/api/programs.php') !== false) {
                // 用户输入了完整URL，提取基础地址
                $api_url = preg_replace('/\/api\/programs\.php.*$/', '', $api_url);
            }

            // 构建完整URL
            $url = rtrim($api_url, '/') . '/api/programs.php?key=' . urlencode($api_key);
            
            // 使用cURL获取数据
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $curl_error = curl_error($ch);
            curl_close($ch);
            
            if ($curl_error) {
                exit(json_encode(array('code' => '请求失败: ' . $curl_error)));
            }
            
            if ($http_code != 200) {
                exit(json_encode(array('code' => 'HTTP错误: ' . $http_code)));
            }
            
            $data = json_decode($response, true);
            if (!$data) {
                exit(json_encode(array('code' => '返回数据解析失败')));
            }
            
            if (isset($data['code']) && $data['code'] != 200) {
                exit(json_encode(array('code' => $data['msg'] ?: 'API返回错误')));
            }
            
            // 检查返回的数据结构
            $programs = array();
            if (isset($data['data']['programs']) && is_array($data['data']['programs'])) {
                $programs = $data['data']['programs'];
            } elseif (isset($data['data']) && is_array($data['data'])) {
                $programs = $data['data'];
            }
            
            if (empty($programs)) {
                exit(json_encode(array('code' => '未获取到程序列表')));
            }
            
            exit(json_encode(array('code' => '获取成功', 'programs' => $programs)));
            break;
            
        case 'import_programs':
            // 异步导入 - 创建导入任务
            $programs_json = isset($_POST['programs']) ? $_POST['programs'] : '';
            $programs = json_decode($programs_json, true);
            $source_api = isset($_POST['source_api']) ? trim($_POST['source_api']) : '';
            $api_key = isset($_POST['api_key']) ? trim($_POST['api_key']) : '';

            import_debug_log('收到导入请求: source_api=' . $source_api . ', api_key_len=' . strlen($api_key) . ', programs_json_len=' . strlen($programs_json));

            if (empty($programs)) {
                import_debug_log('导入失败: 没有要导入的程序 (programs 解码为空)');
                exit(json_encode(array('code' => '没有要导入的程序')));
            }

            if (empty($source_api) || empty($api_key)) {
                import_debug_log('导入失败: 缺少API地址或密钥');
                exit(json_encode(array('code' => '缺少API地址或密钥')));
            }

            // 生成任务ID
            $import_id = md5(uniqid() . time());
            
            // 保存导入任务（使用正确的字符转义）
            $import_id_safe = daddslashes($import_id);
            $source_api_safe = daddslashes($source_api);
            $api_key_safe = daddslashes($api_key);
            $programs_json_safe = $DB->escape($programs_json);
            
            $insert_sql = "INSERT INTO `import_tasks` 
                (`id`, `source_api`, `api_key`, `programs_data`, `status`, `progress`, `created_at`) 
                VALUES 
                ('{$import_id_safe}', '{$source_api_safe}', '{$api_key_safe}', '{$programs_json_safe}', 'pending', 0, NOW())";
            
            $insert_result = $DB->query($insert_sql);
            if (!$insert_result) {
                $err = $DB->error();
                import_debug_log('导入任务创建失败, SQL错误: ' . $err . ' | SQL=' . substr($insert_sql, 0, 300));
                exit(json_encode(array('code' => '创建导入任务失败: ' . $DB->error())));
            }

            // 使用 exec 启动异步任务
            $php_path = 'php'; // 直接使用系统 PATH 中的 php 命令，避免 open_basedir 限制
            $cmd = $php_path . ' ' . escapeshellarg(__DIR__ . '/async_import.php') . ' ' . escapeshellarg($import_id) . ' > /dev/null 2>&1 &';
            $exec_result = @exec($cmd, $output, $ret_code);
            import_debug_log('导入任务已启动: import_id=' . $import_id . ', cmd=' . $cmd . ', ret_code=' . $ret_code);

            exit(json_encode(array(
                'code' => '导入任务已创建',
                'import_id' => $import_id,
                'message' => '正在后台导入，请稍后查看进度'
            )));
            break;
            
        case 'get_import_progress':
            // 获取导入进度
            $import_id = isset($_POST['import_id']) ? trim($_POST['import_id']) : '';
            if (empty($import_id)) {
                exit(json_encode(array('code' => '缺少任务ID')));
            }
            
            $task = $DB->get_row("SELECT * FROM `import_tasks` WHERE `id`='" . daddslashes($import_id) . "'");
            if (!$task) {
                exit(json_encode(array('code' => '任务不存在')));
            }
            
            $result = array(
                'code' => '获取成功',
                'status' => $task['status'],
                'progress' => intval($task['progress']),
                'current_program' => $task['current_program']
            );
            
            if ($task['status'] == 'completed' || $task['status'] == 'failed') {
                $result_data = json_decode($task['result'], true);
                if ($result_data) {
                    $result['imported'] = $result_data['imported'];
                    $result['total'] = $result_data['total'];
                    $result['failed_files'] = $result_data['failed_files'];
                }
            }
            
            exit(json_encode($result));
            break;
            
        case 'regenerate':
            $id = intval($_POST['id']);
            $new_key = bin2hex(random_bytes(32));
            $DB->query("UPDATE `system_api_keys` SET `api_key`='{$new_key}' WHERE `id`={$id}");
            logjl(is_admin_login(), 'API密钥管理', '重新生成API密钥 ID: ' . $id, true);
            exit(json_encode(array('code' => '重新生成成功', 'api_key' => $new_key)));
            break;
    }
}

// 获取所有API密钥
$api_keys = array();
$res = $DB->query("SELECT * FROM `system_api_keys` ORDER BY `created_at` DESC");
while ($row = $DB->fetch($res)) {
    $api_keys[] = $row;
}

// 构建API地址
$api_url = 'http://' . $_SERVER['HTTP_HOST'] . '/api/programs.php?key=YOUR_API_KEY';
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>系统同步 - MLEOE宝塔系统</title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/css/all.min.css">
    <link rel="stylesheet" href="css/style.css?v=2026040501">
    <script src="/static/js/jquery.min.js"></script>
    <script src="/static/js/bootstrap.min.js"></script>
    <style>
        .api-url-box {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .api-url {
            font-family: monospace;
            background: #fff;
            padding: 10px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            word-break: break-all;
        }
        .key-value {
            font-family: monospace;
            background: #f8f9fa;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 12px;
        }
        .usage-info {
            background: #e7f3ff;
            border-left: 4px solid #2196F3;
            padding: 15px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="content-area">
        <div class="card">
            <h3><i class="fas fa-cloud-download-alt"></i> 系统同步</h3>
            
            <div class="usage-info">
                <h5><i class="fas fa-info-circle"></i> 功能说明</h5>
                <p class="mb-2">此功能允许其他系统通过API密钥获取您系统中的程序列表及所有相关信息。</p>
                <p class="mb-0">其他系统管理员可以使用以下API地址获取程序资源：</p>
            </div>
            
            <div class="api-url-box">
                <label class="font-weight-bold">API接口地址：</label>
                <div class="api-url" id="api-url-text"><?php echo htmlspecialchars($api_url); ?></div>
                <small class="text-muted">将 YOUR_API_KEY 替换为下方的实际密钥</small>
                <button class="btn btn-sm btn-secondary mt-2" onclick="copyApiUrl()">
                    <i class="fas fa-copy"></i> 复制地址
                </button>
            </div>
            
            <div class="table-toolbar">
                <div class="toolbar-left">
                    <button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#addKeyModal">
                        <i class="fas fa-plus"></i> 添加密钥
                    </button>
                    <button class="btn btn-success btn-sm" data-toggle="modal" data-target="#importModal" style="margin-left: 10px;">
                        <i class="fas fa-download"></i> 导入程序
                    </button>
                </div>
            </div>
            
            <div class="table-responsive">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th style="width: 50px;">ID</th>
                            <th>密钥名称</th>
                            <th>API密钥</th>
                            <th>状态</th>
                            <th>使用次数</th>
                            <th>创建时间</th>
                            <th>最后使用</th>
                            <th style="width: 200px;">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($api_keys)): ?>
                        <tr>
                            <td colspan="8" class="text-center text-muted">暂无API密钥，请点击"添加密钥"创建</td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($api_keys as $key): ?>
                        <tr>
                            <td><?php echo $key['id']; ?></td>
                            <td><?php echo htmlspecialchars($key['name']); ?></td>
                            <td>
                                <span class="key-value"><?php echo substr($key['api_key'], 0, 16) . '...'; ?></span>
                                <button class="btn btn-sm btn-link" onclick="copyKey('<?php echo $key['api_key']; ?>')">
                                    <i class="fas fa-copy"></i>
                                </button>
                            </td>
                            <td>
                                <?php if ($key['status'] == 1): ?>
                                <span class="badge badge-success">启用</span>
                                <?php else: ?>
                                <span class="badge badge-secondary">禁用</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo number_format($key['use_count']); ?></td>
                            <td><?php echo $key['created_at']; ?></td>
                            <td><?php echo $key['last_used_at'] ? $key['last_used_at'] : '-'; ?></td>
                            <td>
                                <?php if ($key['status'] == 1): ?>
                                <button class="btn btn-sm btn-warning" onclick="toggleKey(<?php echo $key['id']; ?>)">
                                    <i class="fas fa-power-off"></i> 禁用
                                </button>
                                <?php else: ?>
                                <button class="btn btn-sm btn-success" onclick="toggleKey(<?php echo $key['id']; ?>)">
                                    <i class="fas fa-power-off"></i> 启用
                                </button>
                                <?php endif; ?>
                                <button class="btn btn-sm btn-info" onclick="regenerateKey(<?php echo $key['id']; ?>">
                                    <i class="fas fa-sync"></i> 重新生成
                                </button>
                                <button class="btn btn-sm btn-danger" onclick="deleteKey(<?php echo $key['id']; ?>">
                                    <i class="fas fa-trash"></i> 删除
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <!-- 添加密钥模态框 -->
    <div class="modal fade" id="addKeyModal" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加API密钥</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>密钥名称/备注 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="keyName" placeholder="例如：合作伙伴A系统">
                        <small class="form-text text-muted">用于标识此密钥的用途</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addKey()">添加</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 显示完整密钥模态框 -->
    <div class="modal fade" id="showKeyModal" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">API密钥</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle"></i> 请妥善保管此密钥，它只会显示一次！
                    </div>
                    <div class="form-group">
                        <label>完整API密钥</label>
                        <div class="input-group">
                            <input type="text" class="form-control" id="fullKeyValue" readonly>
                            <div class="input-group-append">
                                <button class="btn btn-outline-secondary" type="button" onclick="copyFullKey()">
                                    <i class="fas fa-copy"></i> 复制
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-dismiss="modal">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 从外部系统导入程序模态框 -->
    <div class="modal fade" id="importModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-download"></i> 从外部系统导入程序</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i> 此功能允许您从其他宝塔主机系统获取程序列表并导入到本系统。如果程序ID不同，系统会自动创建新的程序记录。
                    </div>

                    <div id="importStep1">
                        <div class="form-group">
                            <label>外部系统API地址 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="importApiUrl" placeholder="例如：http://example.com">
                            <small class="form-text text-muted">输入对方系统的完整API地址，格式：http://example.com/api/programs.php?key=YOUR_API_KEY</small>
                        </div>
                        <div class="form-group">
                            <label>API密钥 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="importApiKey" placeholder="请输入对方系统提供的API密钥">
                            <small class="form-text text-muted">从对方系统的"系统同步"页面获取API密钥</small>
                        </div>
                        <button type="button" class="btn btn-primary" onclick="fetchPrograms()">
                            <i class="fas fa-search"></i> 获取程序列表
                        </button>
                    </div>

                    <div id="importStep2" style="display: none;">
                        <h6 class="mt-3 mb-2">可导入的程序列表：</h6>
                        <div id="programList" class="table-responsive">
                            <table class="table table-sm table-bordered">
                                <thead>
                                    <tr>
                                        <th style="width: 40px;">
                                            <input type="checkbox" id="selectAll" onchange="toggleSelectAll()">
                                        </th>
                                        <th>原ID</th>
                                        <th>程序名称</th>
                                        <th>类型</th>
                                        <th>版本</th>
                                        <th>状态</th>
                                    </tr>
                                </thead>
                                <tbody id="programTableBody">
                                </tbody>
                            </table>
                        </div>
                        <div class="mt-3">
                            <button type="button" class="btn btn-success" onclick="importSelected()">
                                <i class="fas fa-download"></i> 导入选中的程序
                            </button>
                            <button type="button" class="btn btn-secondary" onclick="resetImport()">
                                <i class="fas fa-undo"></i> 重新获取
                            </button>
                        </div>
                    </div>

                    <div id="importProgress" style="display: none;">
                        <div class="text-center mt-4">
                            <div class="spinner-border text-primary mb-3" role="status">
                                <span class="sr-only">Loading...</span>
                            </div>
                            <h5>正在导入程序...</h5>
                            <div class="progress mt-3" style="height: 25px;">
                                <div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated" 
                                     role="progressbar" style="width: 0%">0%</div>
                            </div>
                            <p id="currentProgram" class="mt-2 text-muted">准备中...</p>
                        </div>
                    </div>

                    <div id="importResult" style="display: none;">
                        <div class="alert alert-success mt-3">
                            <h6><i class="fas fa-check-circle"></i> 导入完成</h6>
                            <p class="mb-0">成功导入 <span id="importedCount">0</span> 个程序<br>
                            共 <span id="totalCount">0</span> 个程序</p>
                        </div>
                        <div id="failedFilesSection" style="display: none;">
                            <div class="alert alert-warning mt-2">
                                <h6><i class="fas fa-exclamation-triangle"></i> 部分文件下载失败</h6>
                                <ul id="failedFilesList" class="mb-0 small"></ul>
                            </div>
                        </div>
                        <button type="button" class="btn btn-primary" onclick="location.reload()">
                            <i class="fas fa-list"></i> 查看程序列表
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
    function addKey() {
        var name = $('#keyName').val().trim();
        if (!name) {
            alert('请输入密钥名称');
            return;
        }
        
        $.post('api_keys.php', {
            action: 'add',
            name: name
        }, function(res) {
            if (res.code === '添加成功') {
                $('#addKeyModal').modal('hide');
                $('#keyName').val('');
                $('#fullKeyValue').val(res.api_key);
                $('#showKeyModal').modal('show');
                // 刷新页面
                $('#showKeyModal').on('hidden.bs.modal', function() {
                    location.reload();
                });
            } else {
                alert(res.code);
            }
        }, 'json');
    }
    
    function deleteKey(id) {
        if (!confirm('确定要删除此API密钥吗？')) return;
        
        $.post('api_keys.php', {
            action: 'delete',
            id: id
        }, function(res) {
            if (res.code === '删除成功') {
                location.reload();
            } else {
                alert(res.code);
            }
        }, 'json');
    }
    
    function copyApiUrl() {
        var apiUrl = document.getElementById('api-url-text').textContent;
        var textarea = document.createElement('textarea');
        textarea.value = apiUrl;
        textarea.style.position = 'fixed';
        textarea.style.opacity = '0';
        document.body.appendChild(textarea);
        textarea.select();
        try {
            document.execCommand('copy');
            alert('API接口地址已复制到剪贴板');
        } catch (err) {
            alert('复制失败，请手动复制');
        }
        document.body.removeChild(textarea);
    }
    
    function toggleKey(id) {
        $.post('api_keys.php', {
            action: 'toggle',
            id: id
        }, function(res) {
            if (res.code === '操作成功') {
                location.reload();
            } else {
                alert(res.code);
            }
        }, 'json');
    }
    
    function regenerateKey(id) {
        if (!confirm('重新生成密钥后，旧密钥将立即失效，确定要继续吗？')) return;
        
        $.post('api_keys.php', {
            action: 'regenerate',
            id: id
        }, function(res) {
            if (res.code === '重新生成成功') {
                $('#fullKeyValue').val(res.api_key);
                $('#showKeyModal').modal('show');
                $('#showKeyModal').on('hidden.bs.modal', function() {
                    location.reload();
                });
            } else {
                alert(res.code);
            }
        }, 'json');
    }
    
    function copyKey(key) {
        copyToClipboard(key);
    }
    
    function copyFullKey() {
        copyToClipboard($('#fullKeyValue').val());
    }
    
    function copyToClipboard(text) {
        var textarea = document.createElement('textarea');
        textarea.value = text;
        textarea.style.position = 'fixed';
        textarea.style.left = '-9999px';
        document.body.appendChild(textarea);
        textarea.select();

        try {
            document.execCommand('copy');
            alert('已复制到剪贴板');
        } catch (err) {
            console.error('复制失败:', err);
            alert('复制失败，请手动复制');
        }

        document.body.removeChild(textarea);
    }

    // 存储获取到的程序列表
    var fetchedPrograms = [];

    function fetchPrograms() {
        var apiUrl = $('#importApiUrl').val().trim();
        var apiKey = $('#importApiKey').val().trim();

        if (!apiUrl) {
            alert('请输入外部系统API地址');
            return;
        }
        if (!apiKey) {
            alert('请输入API密钥');
            return;
        }

        // 显示加载状态
        var btn = event.target;
        var originalText = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 获取中...';
        btn.disabled = true;

        $.post('api_keys.php', {
            action: 'fetch_programs',
            api_url: apiUrl,
            api_key: apiKey
        }, function(res) {
            btn.innerHTML = originalText;
            btn.disabled = false;

            if (res.code === '获取成功') {
                fetchedPrograms = res.programs;
                displayPrograms(fetchedPrograms);
                $('#importStep1').hide();
                $('#importStep2').show();
            } else {
                alert(res.code);
            }
        }, 'json').fail(function() {
            btn.innerHTML = originalText;
            btn.disabled = false;
            alert('请求失败，请检查网络连接');
        });
    }

    function displayPrograms(programs) {
        var html = '';
        programs.forEach(function(program, index) {
            html += '<tr>';
            html += '<td><input type="checkbox" class="program-checkbox" value="' + index + '"></td>';
            html += '<td>' + program.id + '</td>';
            html += '<td>' + escapeHtml(program.name) + '</td>';
            html += '<td>' + (program.type || '-') + '</td>';
            html += '<td>' + (program.version || '-') + '</td>';
            html += '<td>' + (program.status == 1 ? '<span class="badge badge-success">启用</span>' : '<span class="badge badge-secondary">禁用</span>') + '</td>';
            html += '</tr>';
        });
        $('#programTableBody').html(html);
    }

    function escapeHtml(text) {
        if (!text) return '';
        return text
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

    function toggleSelectAll() {
        var checked = $('#selectAll').prop('checked');
        $('.program-checkbox').prop('checked', checked);
    }

    var currentImportId = null;
    var progressInterval = null;

    function importSelected() {
        var selected = [];
        $('.program-checkbox:checked').each(function() {
            selected.push(fetchedPrograms[$(this).val()]);
        });

        if (selected.length === 0) {
            alert('请至少选择一个程序');
            return;
        }

        if (!confirm('确定要导入选中的 ' + selected.length + ' 个程序吗？')) {
            return;
        }

        // 显示进度界面
        $('#importStep2').hide();
        $('#importProgress').show();

        $.post('api_keys.php', {
            action: 'import_programs',
            programs: JSON.stringify(selected),
            source_api: $('#importApiUrl').val().trim(),
            api_key: $('#importApiKey').val().trim()
        }, function(res) {
            if (res.code === '导入任务已创建') {
                currentImportId = res.import_id;
                // 开始轮询进度
                progressInterval = setInterval(function() {
                    checkImportProgress();
                }, 1000);
            } else {
                $('#importProgress').hide();
                $('#importStep2').show();
                alert(res.code);
            }
        }, 'json').fail(function(xhr, status, error) {
            $('#importProgress').hide();
            $('#importStep2').show();
            console.error('导入请求失败:', status, error);
            console.error('响应内容:', xhr.responseText);
            alert('导入失败: ' + (error || '网络错误') + '\n请检查控制台查看详细信息');
        });
    }

    function checkImportProgress() {
        if (!currentImportId) return;

        $.post('api_keys.php', {
            action: 'get_import_progress',
            import_id: currentImportId
        }, function(res) {
            if (res.code === '获取成功') {
                // 更新进度条
                $('#progressBar').css('width', res.progress + '%').text(res.progress + '%');
                
                // 更新当前程序名称
                if (res.current_program) {
                    $('#currentProgram').text('正在导入: ' + res.current_program);
                }

                // 检查是否完成
                if (res.status === 'completed') {
                    clearInterval(progressInterval);
                    showImportResult(res);
                } else if (res.status === 'failed') {
                    clearInterval(progressInterval);
                    $('#importProgress').hide();
                    $('#importStep2').show();
                    alert('导入失败，请重试');
                }
            }
        }, 'json').fail(function(xhr, status, error) {
            console.error('获取进度失败:', status, error);
            console.error('响应内容:', xhr.responseText);
        });
    }

    function showImportResult(res) {
        $('#importProgress').hide();
        $('#importResult').show();
        
        $('#importedCount').text(res.imported || 0);
        $('#totalCount').text(res.total || 0);
        
        // 显示失败的文件
        if (res.failed_files && res.failed_files.length > 0) {
            $('#failedFilesSection').show();
            var html = '';
            res.failed_files.forEach(function(file) {
                html += '<li>' + escapeHtml(file) + '</li>';
            });
            $('#failedFilesList').html(html);
        }
    }

    function resetImport() {
        $('#importStep2').hide();
        $('#importProgress').hide();
        $('#importResult').hide();
        $('#importStep1').show();
        $('#programTableBody').empty();
        $('#progressBar').css('width', '0%').text('0%');
        $('#currentProgram').text('准备中...');
        $('#failedFilesSection').hide();
        fetchedPrograms = [];
        currentImportId = null;
        if (progressInterval) {
            clearInterval(progressInterval);
            progressInterval = null;
        }
    }

    // 模态框关闭时重置状态
    $('#importModal').on('hidden.bs.modal', function() {
        resetImport();
        $('#importApiUrl').val('');
        $('#importApiKey').val('');
    });
    </script>
</body>
</html>
