<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据库配置 - 系统安装</title>
    <link rel="stylesheet" href="/css/admin.css">
    <link rel="icon" href="/img/favicon.png" type="image/png">
</head>
<body>
    <div class="auth-container">
        <div class="auth-box" style="max-width: 600px;">
            <div class="auth-header">
                <div class="auth-logo">
                    <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>
                        <circle cx="8.5" cy="8.5" r="1.5"/>
                        <polyline points="21 15 16 10 5 21"/>
                    </svg>
                </div>
                <h1>数据库配置</h1>
                <p>请配置数据库连接信息</p>
            </div>

            <div class="install-info" style="background: #e3f2fd; border: 1px solid #2196f3; border-radius: 8px; padding: 1rem; margin-bottom: 1.5rem;">
                <p style="margin: 0; color: #1976d2; font-size: 0.9rem;">
                    <strong>默认管理员账号：</strong><br>
                    用户名: <code>admin</code><br>
                    密码: <code>admin123456</code>
                </p>
            </div>

            <form id="install-form" class="auth-form">
                <div class="form-group">
                    <label for="db-type">数据库类型</label>
                    <select id="db-type" name="type" required>
                        <option value="mysql">MySQL</option>
                        <option value="sqlite">SQLite</option>
                    </select>
                </div>

                <!-- MySQL 配置 -->
                <div id="mysql-config">
                    <div class="form-group">
                        <label for="db-host">数据库主机</label>
                        <input type="text" id="db-host" name="host" placeholder="localhost 或远程IP地址" value="localhost">
                        <small>支持远程数据库，请输入IP地址或域名</small>
                    </div>

                    <div class="form-group">
                        <label for="db-port">端口</label>
                        <input type="text" id="db-port" name="port" placeholder="3306" value="3306">
                    </div>

                    <div class="form-group">
                        <label for="db-user">用户名</label>
                        <input type="text" id="db-user" name="user" placeholder="root" value="root" required>
                    </div>

                    <div class="form-group">
                        <label for="db-password">密码</label>
                        <input type="password" id="db-password" name="password" placeholder="数据库密码">
                    </div>

                    <div class="form-group">
                        <label for="db-database">数据库名</label>
                        <input type="text" id="db-database" name="database" placeholder="software_download_center" value="software_download_center" required>
                    </div>

                    <div class="form-group">
                        <label for="db-prefix">表前缀（可选）</label>
                        <input type="text" id="db-prefix" name="table_prefix" placeholder="例如: sd_">
                        <small>留空则无前缀</small>
                    </div>
                </div>

                <!-- SQLite 配置 -->
                <div id="sqlite-config" style="display: none;">
                    <div class="form-group">
                        <label for="db-dsn">数据目录</label>
                        <input type="text" id="db-dsn" name="dsn" placeholder="data" value="data">
                        <small>数据库文件将保存在此目录下</small>
                    </div>
                </div>

                <button type="submit" class="btn btn-primary">
                    <span>保存并连接</span>
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M5 12h14"/>
                        <polyline points="12 5 19 12 12 19"/>
                    </svg>
                </button>
            </form>

            <div id="install-error" class="error-message"></div>
        </div>
    </div>

    <script>
        // 数据库类型切换
        document.getElementById('db-type').addEventListener('change', (e) => {
            const type = e.target.value;
            const mysqlConfig = document.getElementById('mysql-config');
            const sqliteConfig = document.getElementById('sqlite-config');
            
            if (type === 'mysql') {
                mysqlConfig.style.display = 'block';
                sqliteConfig.style.display = 'none';
            } else {
                mysqlConfig.style.display = 'none';
                sqliteConfig.style.display = 'block';
            }
        });

        // 表单提交
        document.getElementById('install-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const formData = new FormData(e.target);
            const data = {
                type: formData.get('type'),
                host: formData.get('host'),
                port: formData.get('port'),
                user: formData.get('user'),
                password: formData.get('password'),
                database: formData.get('database'),
                table_prefix: formData.get('table_prefix'),
                dsn: formData.get('dsn'),
            };

            const submitBtn = e.target.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span>连接中...</span>';

            const errorEl = document.getElementById('install-error');
            errorEl.classList.remove('show');
            errorEl.textContent = '';

            try {
                const response = await fetch('/admin/install/database', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data),
                });

                const result = await response.json();

                if (!response.ok) {
                    throw new Error(result.error || '安装失败');
                }

                alert('数据库配置成功！正在跳转到登录页面...');
                window.location.href = '/admin/login';
            } catch (error) {
                errorEl.textContent = error.message;
                errorEl.classList.add('show');
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            }
        });

        // 检查安装状态
        async function checkInstallStatus() {
            try {
                const response = await fetch('/admin/install/status');
                const data = await response.json();
                
                if (data.initialized) {
                    // 已安装，跳转到登录页
                    window.location.href = '/admin/login';
                }
            } catch (error) {
                console.error('Check install status error:', error);
            }
        }

        // 页面加载时检查
        checkInstallStatus();
    </script>
</body>
</html>
