<?php
ob_start();
require_once '../../config.php';
require_once '../../includes/verify_code_helper.php';
require_once '../../includes/mail_helper.php';
require_once '../../includes/functions.php';

// 如果已经登录，跳转到用户中心
if (isLoggedIn()) {
    header('Location: ' . SITE_URL . 'admin.php');
    exit;
}

$error = '';
$login_method = $_GET['method'] ?? 'code'; // code=验证码登录, password=密码登录

// 处理密码登录
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $login_method === 'password') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    
    // 检查登录失败限制
    $limit = checkLoginLimit($ip);
    if ($limit['locked']) {
        $error = $limit['message'];
    } elseif (empty($username) || empty($password)) {
        $error = '请输入用户名/邮箱和密码';
    } else {
        $stmt = $db->prepare("SELECT id, username, password, role, status, email, email_notify, need_change_password FROM users WHERE username = ? OR email = ?");
        $stmt->bind_param("ss", $username, $username);
        $stmt->execute();
        $result = $stmt->get_result();
        $user = $result->fetch_assoc();

        if ($user && $user['status'] == 1 && password_verify($password, $user['password'])) {
            // 登录成功，清除失败记录
            clearLoginFail($ip);
            
            // 检查是否需要修改密码（第三方用户首次登录）
            if ($user['need_change_password'] == 1) {
                $_SESSION['need_change_password'] = true;
                $_SESSION['temp_user_id'] = $user['id'];
                $_SESSION['temp_username'] = $user['username'];
                header('Location: ' . SITE_URL . 'modules/user/force_change_password.php');
                exit;
            }
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = $user['role'];
            
            // 登录保护提醒
            $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
            $login_time = date('Y-m-d H:i:s');
            
            function getIpLocation($ip) {
                if ($ip == '127.0.0.1' || $ip == 'localhost') return '本地';
                $url = "https://v2.xxapi.cn/api/ip?ip=" . urlencode($ip);
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 3);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $response = curl_exec($ch);
                curl_close($ch);
                $data = json_decode($response, true);
                if ($data && $data['code'] == 200 && !empty($data['data']['address'])) {
                    return $data['data']['address'];
                }
                return '未知位置';
            }
            
            $device_info = getDetailedDeviceInfo($user_agent);
            $device = $device_info['full'];
            $city = getIpLocation($ip);
            
            if (!empty($user['email']) && ($user['email_notify'] ?? 1)) {
                sendLoginAlert($user, $ip, $city, $device, $login_time);
            }
            
            $db->query("INSERT INTO user_login_log (user_id, ip, city, device, user_agent) 
                        VALUES ({$user['id']}, '$ip', '$city', '$device', '" . addslashes($user_agent) . "')");
            
            header('Location: ' . SITE_URL . 'admin.php');
            exit;
        } else {
            $fail_result = recordLoginFail($ip, $username);
            $error = $fail_result['message'];
        }
        $stmt->close();
    }
}

$site_name = getSiteConfig('site_name') ?? '麟泓授权系统';
$sys_version = getSiteConfig('sys_version') ?? '1.0.0';

// 获取启用的快捷登录方式
$enabled_logins = $db->fetchAll("SELECT type, name FROM quick_login_config WHERE enabled = 1 ORDER BY sort ASC");

// 登录方式配置
$login_styles = [
    'qq' => ['bg' => '#12B7F5', 'icon' => 'qq.svg', 'url' => '/api/qq_login.php'],
    'wx' => ['bg' => '#07C160', 'icon' => 'wechat.svg', 'url' => '/api/union_login.php?type=wx'],
    'alipay' => ['bg' => '#1677FF', 'icon' => 'alipay.svg', 'url' => '/api/union_login.php?type=alipay'],
    'gitee' => ['bg' => '#C71D23', 'icon' => 'gitee.svg', 'url' => '/api/gitee_login.php'],
    'sina' => ['bg' => '#FF8200', 'icon' => 'weibo.svg', 'url' => '/api/union_login.php?type=sina'],
    'baidu' => ['bg' => '#2932E1', 'icon' => 'baidu.svg', 'url' => '/api/union_login.php?type=baidu'],
    'xiaomi' => ['bg' => '#FF6900', 'icon' => 'xiaomi.svg', 'url' => '/api/union_login.php?type=xiaomi'],
    'huawei' => ['bg' => '#FF0000', 'icon' => 'huawei.svg', 'url' => '/api/union_login.php?type=huawei'],
    'douyin' => ['bg' => '#000000', 'icon' => 'douyin.svg', 'url' => '/api/union_login.php?type=douyin'],
    'google' => ['bg' => '#4285F4', 'icon' => 'google.svg', 'url' => '/api/union_login.php?type=google'],
    'microsoft' => ['bg' => '#00A4EF', 'icon' => 'microsoft.svg', 'url' => '/api/union_login.php?type=microsoft'],
    'facebook' => ['bg' => '#1877F2', 'icon' => 'facebook.svg', 'url' => '/api/union_login.php?type=facebook'],
    'twitter' => ['bg' => '#1DA1F2', 'icon' => 'twitter.svg', 'url' => '/api/union_login.php?type=twitter'],
    'feishu' => ['bg' => '#00C4A0', 'icon' => 'feishu.svg', 'url' => '/api/feishu_login.php'],
    'wework' => ['bg' => '#2C7A3E', 'icon' => 'wework.svg', 'url' => '/api/union_login.php?type=wework'],
    'dingtalk' => ['bg' => '#1E9AEF', 'icon' => 'dingtalk.svg', 'url' => '/api/union_login.php?type=dingtalk'],
    'github' => ['bg' => '#24292E', 'icon' => 'github.svg', 'url' => '/api/github_login.php'],
    'lhouath' => ['bg' => '#ffffff', 'icon' => 'lhouath.svg', 'url' => '/api/lhouath_login.php'],
];
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录 - <?php echo htmlspecialchars($site_name); ?></title>
    <link rel="stylesheet" href="/assets/css/style.css">
    <link rel="stylesheet" href="/assets/css/dark.css" id="dark-theme" disabled>
    <script src="/assets/js/main.js" defer></script>
    <link rel="stylesheet" href="/assets/css/app.css">
    <script src="/assets/js/iconify.min.js"></script>
    <link rel="icon" href="/assets/uploads/favicon.ico">
    <!-- 提前加载二维码库，避免动态加载延迟 -->
    <script src="/assets/js/qrcode.min.js"></script>
    <style>
        body {
    width: 100%;
    min-height: 100vh;
    background: linear-gradient(135deg, #e0f2fe 0%, #bae6fd 50%, #f0f9ff 100%);
    background-size: cover;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
    margin: 0;
}
        #qrcodeLoginStatus {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
}
        .auth-card {
            max-width: 450px;
            margin: 50px auto;
            background: var(--bg-primary);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
        }
        .auth-header {
            text-align: center;
            margin-bottom: 20px;
        }
        .auth-header h1 {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 6px;
        }
        .auth-header p {
            color: var(--text-secondary);
            font-size: 14px;
        }
        .login-tabs {
            display: flex;
            margin-bottom: 28px;
            background: var(--bg-secondary);
            border-radius: 40px;
            padding: 4px;
        }
        .login-tab {
            flex: 1;
            text-align: center;
            padding: 10px 12px;
            cursor: pointer;
            color: var(--text-secondary);
            font-weight: 500;
            font-size: 14px;
            transition: all 0.2s;
            border-radius: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }
        .login-tab.active {
            background: var(--primary-color);
            color: white;
        }
        .login-panel {
            display: none;
        }
        .login-panel.active {
            display: block;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: flex;
            align-items: center;
            gap: 6px;
            margin-bottom: 8px;
            font-weight: 500;
            font-size: 14px;
        }
        .form-group input {
            width: 100%;
            padding: 12px 16px;
            border: 1.5px solid var(--border-color);
            border-radius: 12px;
            background: var(--bg-primary);
            color: var(--text-primary);
            font-size: 14px;
            box-sizing: border-box;
            transition: all 0.2s;
        }
        .form-group input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        .code-input-group {
            display: flex;
            gap: 10px;
        }
        .code-input-group input {
            flex: 1;
        }
        .code-input-group button {
            padding: 0 20px;
            white-space: nowrap;
            border-radius: 12px;
            border: 1.5px solid var(--border-color);
            background: var(--bg-secondary);
            color: var(--text-primary);
            cursor: pointer;
            font-size: 13px;
            font-weight: 500;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            gap: 4px;
        }
        .code-input-group button:hover {
            border-color: #667eea;
            background: rgba(102, 126, 234, 0.05);
        }
        .code-input-group button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        .btn-primary {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            transition: all 0.2s;
        }
        .btn-primary:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }
        .btn-primary:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        .auth-footer {
            text-align: center;
            margin-top: 20px;
        }
        .auth-footer a {
            color: #667eea;
            text-decoration: none;
            font-weight: 500;
        }
        .auth-footer a:hover {
            text-decoration: underline;
        }
        .alert {
            padding: 12px 16px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: none;
            align-items: center;
            gap: 8px;
        }
        .alert-error {
            background: rgba(239,68,68,0.1);
            border: 1px solid #ef4444;
            color: #ef4444;
        }
        .alert-success {
            background: rgba(16,185,129,0.1);
            border: 1px solid #10b981;
            color: #10b981;
        }
        /* 圆形图标样式 */
        .login-icons {
            display: flex;
            justify-content: center;
            gap: 16px;
            flex-wrap: wrap;
            margin-top: 20px;
        }
        .login-icon {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 48px;
            height: 48px;
            border-radius: 50%;
            transition: transform 0.2s, box-shadow 0.2s;
            text-decoration: none;
        }
        .login-icon:hover {
            transform: scale(1.1);
        }
        .login-icon img {
            width: 26px;
            height: 26px;
        }
        .loading-spinner {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid rgba(255,255,255,0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 0.6s linear infinite;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        @media (max-width: 768px) {
            .auth-card [style*="display: flex"] {
                flex-direction: column !important;
            }
            .auth-card [style*="border-right"] {
                border-right: none !important;
                border-bottom: 1px solid var(--border-color);
                padding-bottom: 20px;
                margin-bottom: 20px;
            }
        }
/* 右侧固定按钮组 */
.fixed-right-buttons {
    position: fixed;
    top: 20px;
    right: 0;
    z-index: 99999;
    display: flex;
    flex-direction: column;
    gap: 10px;
    align-items: flex-end; /* 按钮右对齐 */
}

.fixed-right-btn {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    gap: 8px;
    width: 140px; /* 固定宽度 */
    padding: 12px 0 12px 20px;
    color: white;
    border-radius: 40px 0 0 40px;
    text-decoration: none;
    font-size: 14px;
    font-weight: 600;
    box-shadow: -4px 4px 16px rgba(0,0,0,0.15);
    transition: all 0.3s ease;
    white-space: nowrap;
    box-sizing: border-box;
}

.fixed-right-btn.download {
    background: linear-gradient(135deg, #3b82f6, #2563eb);
}

.fixed-right-btn.service {
    background: linear-gradient(135deg, #10b981, #059669);
}

/* 悬停效果 - 只改变宽度和左内边距 */
.fixed-right-btn:hover {
    width: 155px;
    padding-left: 30px;
    box-shadow: -6px 6px 20px rgba(0,0,0,0.2);
}

.fixed-right-btn img {
    filter: brightness(0) invert(1);
    flex-shrink: 0; /* 图标不缩小 */
}

.fixed-right-btn span {
    flex-shrink: 0; /* 文字不换行 */
}

/* 移动端隐藏 */
@media (max-width: 768px) {
    .fixed-right-buttons {
        display: none !important;
    }
}
    </style>
</head>
<body>
<!-- 右侧固定按钮组 -->
<div class="fixed-right-buttons">
    <a href="/modules/home/downloads.php" class="fixed-right-btn download">
        <img src="https://api.iconify.design/mdi:cellphone-arrow-down.svg?color=white" width="20" height="20" alt="">
        <span>下载APP</span>
    </a>
    <a href="/modules/home/faq.php#contact" class="fixed-right-btn service">
        <img src="https://api.iconify.design/mdi:headset.svg?color=white" width="20" height="20" alt="">
        <span>联系客服</span>
    </a>
</div>
<div class="auth-card" style="max-width: 900px;">
    <div class="auth-header">
        <img src="/assets/uploads/logo_1774667898.png" alt="Logo" style="display: block; margin: 0 auto 15px auto; height: 60px;">
        <h1>
            <img src="https://api.iconify.design/mdi:login.svg?color=%23667eea" width="24" height="24" alt="">
            登录账号
        </h1>
        <p>欢迎回来</p>
    </div>
    
    <!-- 左右两列布局 -->
    <div style="display: flex; gap: 30px; min-height: 400px;">
        <!-- 左侧：扫码登录 -->
        <div style="flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 20px; border-right: 1px solid var(--border-color);">
            <div style="text-align: center; margin-bottom: 16px;">
                <h3 style="margin-top: 8px; font-size: 16px; font-weight: 600; color: var(--text-primary);">扫码登录</h3>
                <p style="font-size: 12px; color: var(--text-muted); margin-top: 4px;">使用手机扫描二维码</p>
            </div>
            
            <!-- 二维码容器 -->
            <div id="qrcodeLoginContainer" style="display: flex; justify-content: center; margin-bottom: 16px;">
                <div id="qrcodeLogin" style="width: 200px; height: 200px; background: #f8fafc; border-radius: 16px; display: flex; align-items: center; justify-content: center;">
                    <img src="https://api.iconify.design/mdi:loading.svg?color=%2394a3b8" width="40" height="40" style="animation: spin 1s linear infinite;" alt="">
                </div>
            </div>
            
            <div id="qrcodeLoginStatus" style="text-align: center; font-size: 13px; color: var(--text-secondary); min-height: 40px;">
                等待扫描...
            </div>
            
            <div style="display: flex; align-items: center; gap: 8px; margin-top: 10px;">
                <img src="https://api.iconify.design/mdi:clock-outline.svg?color=%2394a3b8" width="14" height="14" alt="">
                <span id="qrcodeRefreshCountdown" style="font-size: 12px; color: var(--text-muted);">30秒后刷新</span>
                <a href="javascript:;" onclick="refreshQrcodeLogin()" style="color: #667eea; font-size: 12px; text-decoration: none;">刷新</a>
            </div>
        </div>
        
        <!-- 右侧：账号密码/验证码登录 -->
        <div style="flex: 1; padding: 20px 10px;">
            <!-- 切换标签 -->
            <div class="login-tabs">
                <div class="login-tab <?php echo $login_method == 'code' ? 'active' : ''; ?>" data-method="code">
                    <img src="https://api.iconify.design/mdi:message-text.svg?color=<?php echo $login_method == 'code' ? 'white' : '%236b7280'; ?>" width="16" height="16" alt="">
                    验证码登录
                </div>
                <div class="login-tab <?php echo $login_method == 'password' ? 'active' : ''; ?>" data-method="password">
                    <img src="https://api.iconify.design/mdi:lock.svg?color=<?php echo $login_method == 'password' ? 'white' : '%236b7280'; ?>" width="16" height="16" alt="">
                    密码登录
                </div>
            </div>
            
            <div id="message" class="alert"></div>
            
            <!-- 验证码登录面板 -->
            <div id="codePanel" class="login-panel <?php echo $login_method == 'code' ? 'active' : ''; ?>">
                <form id="codeLoginForm">
                    <div class="form-group">
                        <label><img src="https://api.iconify.design/mdi:email.svg?color=%23667eea" width="18" height="18" alt="">邮箱</label>
                        <div class="code-input-group">
                            <input type="email" id="code_email" name="email" placeholder="请输入邮箱" required>
                            <button type="button" id="sendCodeBtn">发送验证码</button>
                        </div>
                    </div>
                    <div class="form-group">
                        <label><img src="https://api.iconify.design/mdi:shield-key.svg?color=%23667eea" width="18" height="18" alt="">验证码</label>
                        <input type="text" id="code" name="code" placeholder="请输入6位验证码" required>
                    </div>
                    <button type="submit" class="btn-primary" id="codeLoginBtn">登 录</button>
                </form>
            </div>
            
            <!-- 密码登录面板 -->
            <div id="passwordPanel" class="login-panel <?php echo $login_method == 'password' ? 'active' : ''; ?>">
                <form method="POST" action="?method=password">
                    <div class="form-group">
                        <label><img src="https://api.iconify.design/mdi:account.svg?color=%23667eea" width="18" height="18" alt="">用户名 / 邮箱</label>
                        <input type="text" name="username" placeholder="请输入用户名或邮箱" required>
                    </div>
                    <div class="form-group">
                        <label><img src="https://api.iconify.design/mdi:lock.svg?color=%23667eea" width="18" height="18" alt="">密码</label>
                        <input type="password" name="password" placeholder="请输入密码" required>
                    </div>
                    <?php if ($error): ?>
                        <div class="alert alert-error" style="display: flex;">
                            <img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23ef4444" width="18" height="18" alt="">
                            <?php echo htmlspecialchars($error); ?>
                        </div>
                    <?php endif; ?>
                    <button type="submit" class="btn-primary">登 录</button>
                </form>
            </div>
            
            <!-- 快捷登录图标 -->
            <div style="margin-top: 30px;">
                <div style="display: flex; align-items: center; gap: 16px; justify-content: center;">
                    <a href="javascript:;" onclick="showWechatLogin()" class="login-icon" style="background: #07C160; width: 40px; height: 40px;">
                        <img src="https://api.iconify.design/mdi:wechat.svg?color=white" width="22" height="22" alt="">
                    </a>
                    <?php foreach (array_slice($enabled_logins, 0, 4) as $login): 
                        $type = $login['type'];
                        $style = $login_styles[$type] ?? ['bg' => '#667eea', 'icon' => 'default.svg', 'url' => '#'];
                    ?>
                        <a href="<?php echo $style['url']; ?>" class="login-icon" style="background: <?php echo $style['bg']; ?>; width: 40px; height: 40px;">
                            <img src="/assets/svg/<?php echo $style['icon']; ?>" alt="<?php echo $login['name']; ?>">
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 底部链接 -->
   
        <div class="auth-footer" style="margin-top: 0;">
            
        
<p>还没有账号？<a href="/modules/home/register.php">立即注册</a></p>
    </div>
</div>

<script>
// ========== 微信验证码登录（反向验证版） ==========
let wechatPollingTimer = null;
let wechatCurrentToken = null;
let wechatVerifyCode = null;

async function showWechatLogin() {
    try {
        const res = await fetch('/api/wechat-qrcode.php');
        const data = await res.json();
        if (data.code === 0) {
            wechatCurrentToken = data.token;
            wechatVerifyCode = data.verify_code;
        } else {
            alert('生成验证码失败');
            return;
        }
    } catch (e) {
        alert('网络错误');
        return;
    }
    
    const html = `
        <div id="wechatLoginModal" style="position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.5);backdrop-filter:blur(4px);z-index:9999;display:flex;align-items:center;justify-content:center;" onclick="if(event.target===this)this.remove()">
    <div style="background:white;border-radius:28px;padding:32px 24px;width:90%;max-width:380px;text-align:center;box-shadow:0 20px 40px rgba(0,0,0,0.15);" onclick="event.stopPropagation()">
        
        <!-- 标题 -->
        <div style="display:flex;align-items:center;justify-content:center;gap:8px;margin-bottom:24px;">
            <div style="width:40px;height:40px;background:#07C160;border-radius:12px;display:flex;align-items:center;justify-content:center;">
                <img src="https://api.iconify.design/mdi:wechat.svg?color=white" width="22" height="22" alt="">
            </div>
            <span style="font-size:20px;font-weight:700;color:#1a1a1a;">微信登录</span>
        </div>
        
        <!-- 步骤 -->
        <div style="display:flex;justify-content:center;gap:24px;margin-bottom:20px;">
            <div style="text-align:center;">
                <div style="width:32px;height:32px;background:#07C16010;border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 8px;">
                    <span style="color:#07C160;font-weight:700;font-size:14px;">1</span>
                </div>
                <span style="font-size:12px;color:#666;">扫码关注</span>
            </div>
            <div style="color:#ddd;font-size:20px;">→</div>
            <div style="text-align:center;">
                <div style="width:32px;height:32px;background:#07C16010;border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 8px;">
                    <span style="color:#07C160;font-weight:700;font-size:14px;">2</span>
                </div>
                <span style="font-size:12px;color:#666;">发送验证码</span>
            </div>
            <div style="color:#ddd;font-size:20px;">→</div>
            <div style="text-align:center;">
                <div style="width:32px;height:32px;background:#07C16010;border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 8px;">
                    <span style="color:#07C160;font-weight:700;font-size:14px;">3</span>
                </div>
                <span style="font-size:12px;color:#666;">自动登录</span>
            </div>
        </div>
        
        <!-- 二维码 -->
        <div style="display:flex;justify-content:center;margin-bottom:20px;">
            <img src="/assets/uploads/wechat.jpg" style="width:200px;height:200px;border-radius:16px;box-shadow:0 4px 16px rgba(0,0,0,0.1);" alt="公众号二维码">
        </div>
        
        <!-- 验证码 -->
        <div style="background:linear-gradient(135deg,#f8f8f8 0%,#ffffff 100%);padding:20px;border-radius:20px;margin-bottom:16px;border:1px solid #f0f0f0;">
            <p style="color:#999;font-size:12px;margin-bottom:8px;letter-spacing:1px;">验证码</p>
            <div style="font-size:52px;font-weight:800;letter-spacing:12px;color:#07C160;font-family:'Courier New',monospace;text-shadow:0 2px 4px rgba(7,193,96,0.1);">${wechatVerifyCode}</div>
            <p style="color:#999;font-size:11px;margin-top:8px;display:flex;align-items:center;justify-content:center;gap:4px;">
                <img src="https://api.iconify.design/mdi:clock-outline.svg?color=%23999" width="12" height="12" alt="">
                有效期 5 分钟
            </p>
        </div>
        
        <!-- 状态 -->
        <p id="wechatStatus" style="color:#07C160;font-size:14px;margin-bottom:16px;display:flex;align-items:center;justify-content:center;gap:6px;">
            <img src="https://api.iconify.design/mdi:loading.svg?color=%2307C160" width="16" height="16" style="animation:spin 1s linear infinite;" alt="">
            <span>等待发送验证码...</span>
        </p>
        
        <!-- 按钮 -->
        <button onclick="closeWechatModal()" style="width:100%;padding:14px;background:#f5f5f5;border:none;border-radius:14px;font-size:15px;font-weight:500;color:#666;cursor:pointer;transition:all 0.2s;" onmouseover="this.style.background='#eee'" onmouseout="this.style.background='#f5f5f5'">取消</button>
    </div>
</div>

<style>
@keyframes spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}
</style>
    `;
    document.body.insertAdjacentHTML('beforeend', html);
    startWechatPolling();
}

function closeWechatModal() {
    if (wechatPollingTimer) {
        clearInterval(wechatPollingTimer);
        wechatPollingTimer = null;
    }
    document.getElementById('wechatLoginModal')?.remove();
}

function startWechatPolling() {
    let count = 0;
    const maxCount = 150;
    wechatPollingTimer = setInterval(async () => {
        count++;
        if (!wechatCurrentToken) return;
        try {
            const res = await fetch('/api/wechat-check.php?token=' + wechatCurrentToken);
            const data = await res.json();
            const statusEl = document.getElementById('wechatStatus');
            if (data.status === 'verified') {
                statusEl.innerHTML = '验证码已收到，正在登录...';
                statusEl.style.color = '#10b981';
                clearInterval(wechatPollingTimer);
                setTimeout(() => { window.location.href = data.redirect || '/admin.php'; }, 1000);
            } else if (data.status === 'success') {
                clearInterval(wechatPollingTimer);
                window.location.href = data.redirect || '/admin.php';
            } else if (data.status === 'waiting') {
                statusEl.innerHTML = '等待发送验证码...';
            }
            if (count >= maxCount) {
                clearInterval(wechatPollingTimer);
                statusEl.innerHTML = '验证码已过期，请重新获取';
                statusEl.style.color = '#ef4444';
            }
        } catch (e) {
            console.error('轮询错误:', e);
        }
    }, 2000);
}

let countdown = 0;
let timer = null;

// 切换登录方式
document.querySelectorAll('.login-tab').forEach(tab => {
    tab.addEventListener('click', function() {
        const method = this.dataset.method;
        window.history.pushState({}, '', '?method=' + method);
        document.querySelectorAll('.login-tab').forEach(t => t.classList.remove('active'));
        this.classList.add('active');
        document.getElementById('codePanel').classList.remove('active');
        document.getElementById('passwordPanel').classList.remove('active');
        if (method === 'code') {
            document.getElementById('codePanel').classList.add('active');
        } else {
            document.getElementById('passwordPanel').classList.add('active');
        }
        document.querySelectorAll('.login-tab img').forEach(img => {
            const parent = img.closest('.login-tab');
            if (parent.classList.contains('active')) {
                img.style.filter = 'brightness(0) invert(1)';
            } else {
                img.style.filter = 'none';
            }
        });
    });
});

function showMessage(msg, type) {
    const msgDiv = document.getElementById('message');
    const icon = type === 'error' 
        ? '<img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23ef4444" width="18" height="18" alt="">'
        : '<img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="18" height="18" alt="">';
    msgDiv.innerHTML = icon + ' ' + msg;
    msgDiv.className = 'alert alert-' + type;
    msgDiv.style.display = 'flex';
    setTimeout(() => { msgDiv.style.display = 'none'; }, 3000);
}

function startCountdown(seconds) {
    const btn = document.getElementById('sendCodeBtn');
    countdown = seconds;
    btn.disabled = true;
    btn.innerHTML = `<img src="https://api.iconify.design/mdi:clock-outline.svg?color=currentColor" width="14" height="14" alt="">重新发送(${countdown}s)`;
    timer = setInterval(() => {
        countdown--;
        if (countdown <= 0) {
            clearInterval(timer);
            btn.disabled = false;
            btn.innerHTML = '<img src="https://api.iconify.design/mdi:send.svg?color=currentColor" width="14" height="14" alt="">发送验证码';
        } else {
            btn.innerHTML = `<img src="https://api.iconify.design/mdi:clock-outline.svg?color=currentColor" width="14" height="14" alt="">重新发送(${countdown}s)`;
        }
    }, 1000);
}

// 发送验证码
document.getElementById('sendCodeBtn')?.addEventListener('click', async function() {
    const email = document.getElementById('code_email').value;
    if (!email) { showMessage('请输入邮箱', 'error'); return; }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { showMessage('邮箱格式不正确', 'error'); return; }
    this.disabled = true;
    this.innerHTML = '<span class="loading-spinner"></span> 发送中...';
    try {
        const response = await fetch('/api/send_code.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `email=${encodeURIComponent(email)}&type=login`
        });
        const data = await response.json();
        if (data.success) {
            showMessage(data.message, 'success');
            startCountdown(60);
        } else {
            showMessage(data.message, 'error');
            this.disabled = false;
            this.innerHTML = '<img src="https://api.iconify.design/mdi:send.svg?color=currentColor" width="14" height="14" alt="">发送验证码';
        }
    } catch (error) {
        showMessage('网络错误，请重试', 'error');
        this.disabled = false;
        this.innerHTML = '<img src="https://api.iconify.design/mdi:send.svg?color=currentColor" width="14" height="14" alt="">发送验证码';
    }
});

// 验证码登录提交
document.getElementById('codeLoginForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    const email = document.getElementById('code_email').value;
    const code = document.getElementById('code').value;
    if (!email || !code) { showMessage('请输入邮箱和验证码', 'error'); return; }
    const loginBtn = document.getElementById('codeLoginBtn');
    loginBtn.disabled = true;
    loginBtn.innerHTML = '<span class="loading-spinner"></span> 登录中...';
    try {
        const response = await fetch('/api/verify_code.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `type=login&login_email=${encodeURIComponent(email)}&login_code=${encodeURIComponent(code)}`
        });
        const data = await response.json();
        if (data.success) {
            showMessage(data.message, 'success');
            setTimeout(() => { window.location.href = '/admin.php'; }, 1000);
        } else {
            showMessage(data.message, 'error');
            loginBtn.disabled = false;
            loginBtn.innerHTML = '<img src="https://api.iconify.design/mdi:login.svg?color=white" width="18" height="18" alt="">登 录';
        }
    } catch (error) {
        showMessage('网络错误，请重试', 'error');
        loginBtn.disabled = false;
        loginBtn.innerHTML = '<img src="https://api.iconify.design/mdi:login.svg?color=white" width="18" height="18" alt="">登 录';
    }
});

// ========== 左侧二维码登录（立即初始化，不再等待DOMContentLoaded） ==========
let qrcodeLoginTimer = null;
let qrcodeLoginCountdown = 30;
let qrcodeLoginToken = null;
let qrcodeLoginPolling = null;
let qrcodeLoginInstance = null;

function generateQrcodeLogin() {
    const container = document.getElementById('qrcodeLogin');
    const statusEl = document.getElementById('qrcodeLoginStatus');
    if (!container) return;
    container.innerHTML = '<img src="https://api.iconify.design/mdi:loading.svg?color=%2394a3b8" width="40" height="40" style="animation: spin 1s linear infinite;" alt="">';
    
    fetch('/api/get_config.php')
        .then(res => res.json())
        .then(configData => {
            const appId = configData.data.lhouath_app_id;
            
            // 判断 app_id 是否为空
            if (!appId) {
                container.innerHTML = '<img src="https://api.iconify.design/mdi:qrcode-scan.svg?color=%239ca3af" width="40" height="40" alt="">';
                statusEl.innerHTML = '扫码功能未配置';
                showQrcodeConfigAlert();
                return;
            }
            
            return fetch('https://open.lhwks.cn/api/qrcode_generate.php?app_id=' + appId);
        })
        .then(res => res ? res.json() : null)
        .then(data => {
            if (!data) return;
            if (data.token) {
                qrcodeLoginToken = data.token;
                container.innerHTML = '';
                qrcodeLoginInstance = new QRCode(container, {
                    text: data.qrcode_url,
                    width: 200,
                    height: 200,
                    colorDark: '#1f2937',
                    colorLight: '#ffffff',
                    correctLevel: QRCode.CorrectLevel.M
                });
                statusEl.innerHTML = '请使用手机扫描二维码';
                statusEl.style.color = '';
                startQrcodePolling();
                startQrcodeCountdown();
            }
        });
}

// 弹窗提示
function showQrcodeConfigAlert() {
    const modal = document.createElement('div');
    modal.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.5);backdrop-filter:blur(4px);z-index:99999;display:flex;align-items:center;justify-content:center;';
    modal.onclick = function(e) { if (e.target === modal) modal.remove(); };
    modal.innerHTML = `
        <div style="background:white;border-radius:20px;padding:32px;max-width:400px;width:90%;text-align:center;box-shadow:0 20px 40px rgba(0,0,0,0.15);" onclick="event.stopPropagation()">
            <div style="width:56px;height:56px;background:#fef3c7;border-radius:16px;display:flex;align-items:center;justify-content:center;margin:0 auto 16px;">
                <img src="https://api.iconify.design/mdi:qrcode-scan.svg?color=%23d97706" width="28" height="28" alt="">
            </div>
            <h3 style="font-size:18px;font-weight:700;color:#1a1a1a;margin-bottom:8px;">扫码功能暂不可用</h3>
            <p style="color:#64748b;font-size:14px;margin-bottom:24px;">扫码登录功能尚未配置，请联系管理员</p>
            <p style="color:#64748b;font-size:14px;margin-bottom:24px;">如果您是管理员可以前往后台的登陆配置中配置</p>
            <button onclick="this.closest('div').parentElement.remove()" style="width:100%;padding:12px;background:#d97706;color:white;border:none;border-radius:12px;font-size:14px;cursor:pointer;">知道了</button>
        </div>
    `;
    document.body.appendChild(modal);
}
function startQrcodeCountdown() {
    qrcodeLoginCountdown = 30;
    const countdownEl = document.getElementById('qrcodeRefreshCountdown');
    if (qrcodeLoginTimer) clearInterval(qrcodeLoginTimer);
    qrcodeLoginTimer = setInterval(() => {
        qrcodeLoginCountdown--;
        countdownEl.textContent = qrcodeLoginCountdown + '秒后刷新';
        if (qrcodeLoginCountdown <= 0) {
            clearInterval(qrcodeLoginTimer);
            refreshQrcodeLogin();
        }
    }, 1000);
}

function refreshQrcodeLogin() {
    if (qrcodeLoginPolling) clearInterval(qrcodeLoginPolling);
    if (qrcodeLoginTimer) clearInterval(qrcodeLoginTimer);
    generateQrcodeLogin();
}

function startQrcodePolling() {
    let count = 0;
    const maxCount = 150;
    const statusEl = document.getElementById('qrcodeLoginStatus');
    if (qrcodeLoginPolling) clearInterval(qrcodeLoginPolling);
    qrcodeLoginPolling = setInterval(() => {
        count++;
        if (!qrcodeLoginToken) return;
        fetch('https://open.lhwks.cn/api/qrcode_status.php?token=' + qrcodeLoginToken)
            .then(res => res.json())
            .then(data => {
                if (data.status == 1) {
                    statusEl.innerHTML = '已扫码，请在手机上确认';
                    statusEl.style.color = '#10b981';
                }  else if (data.status == 2 && data.code) {
                    clearInterval(qrcodeLoginPolling);
                    clearInterval(qrcodeLoginTimer);
                    statusEl.innerHTML = '登录成功，正在跳转...';
                    window.location.href = '/api/lhouath_callback.php?code=' + data.code;
                } else if (data.status == 3) {
                    statusEl.innerHTML = '二维码已过期';
                    statusEl.style.color = '#ef4444';
                }
                if (count >= maxCount) clearInterval(qrcodeLoginPolling);
            });
    }, 2000);
}
// 立即初始化二维码（不等待任何事件）
(function() {
    function tryInitQrcode() {
        if (typeof QRCode !== 'undefined' && document.getElementById('qrcodeLogin')) {
            generateQrcodeLogin();
        } else {
            setTimeout(tryInitQrcode, 20);
        }
    }
    tryInitQrcode();
})();

// 为其他代码保留兼容（如果还有地方调用 initQrcodeLogin）
function initQrcodeLogin() {
    // 空函数，实际已通过 tryInitQrcode 初始化
}
</script>
</body>
</html>