<?php
/**
 * APP访问管理页面
 * 用户可以生成二维码和密钥来授权APP管理虚拟空间
 */

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

// 检查用户登录
$user = is_user_login();
if (!$user) {
    header('Location: /user/login.php');
    exit;
}

// 获取当前用户的令牌列表
$DB = $GLOBALS['DB'];
$tokens = $DB->get_all("SELECT 
    `id`, `token`, `token_type`, `expire_time`, `max_uses`, `used_count`, `status`, `confirm_status`, `confirm_expire_time`, `app_device_info`, `create_time`, `last_use_time` 
    FROM `app_access_tokens` 
    WHERE `user_id`='{$user['id']}' 
    ORDER BY `create_time` DESC");

// 页面标题
$page_title = 'APP访问管理';
?>
<!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 $page_title; ?> - <?php echo $conf['title']; ?></title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css?v=20260406_1">
    <link rel="stylesheet" href="/static/css/all.min.css?v=20260406_1">
    <link rel="stylesheet" href="css/style.css?v=20260406_1">
    <style>
        .access-card {
            background: #fff;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        }
        .token-item {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            border-left: 4px solid #007bff;
        }
        .token-item.qrcode {
            border-left-color: #28a745;
        }
        .token-item.key {
            border-left-color: #ffc107;
        }
        .token-item.expired {
            border-left-color: #dc3545;
            opacity: 0.7;
        }
        .qrcode-display {
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
        }
        .key-display {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            font-family: monospace;
            word-break: break-all;
            border: 2px dashed #007bff;
        }
        .btn-generate {
            padding: 12px 30px;
            font-size: 16px;
            border-radius: 25px;
        }
        /* 信息卡片样式 */
        .info-card {
            display: flex;
            align-items: flex-start;
            padding: 16px;
            border-radius: 10px;
            height: 100%;
            transition: transform 0.2s, box-shadow 0.2s;
        }
        .info-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        .info-card-blue {
            background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
            border: 1px solid #90caf9;
        }
        .info-card-orange {
            background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
            border: 1px solid #ffcc80;
        }
        .info-card-green {
            background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
            border: 1px solid #a5d6a7;
        }
        .info-card-red {
            background: linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%);
            border: 1px solid #ef9a9a;
        }
        .info-card-icon {
            width: 44px;
            height: 44px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            margin-right: 14px;
            flex-shrink: 0;
        }
        .info-card-blue .info-card-icon {
            background: #1976d2;
            color: #fff;
        }
        .info-card-orange .info-card-icon {
            background: #f57c00;
            color: #fff;
        }
        .info-card-green .info-card-icon {
            background: #388e3c;
            color: #fff;
        }
        .info-card-red .info-card-icon {
            background: #d32f2f;
            color: #fff;
        }
        .info-card-content {
            flex: 1;
        }
        .info-card-content h6 {
            font-weight: 600;
            margin-bottom: 6px;
            font-size: 15px;
        }
        .info-card-blue .info-card-content h6 {
            color: #1565c0;
        }
        .info-card-orange .info-card-content h6 {
            color: #e65100;
        }
        .info-card-green .info-card-content h6 {
            color: #2e7d32;
        }
        .info-card-red .info-card-content h6 {
            color: #c62828;
        }
        .info-card-content p {
            font-size: 13px;
            color: #555;
            margin-bottom: 8px;
            line-height: 1.5;
        }
        .info-card-content ul {
            margin: 0;
            padding-left: 16px;
            font-size: 12px;
            color: #666;
        }
        .info-card-content ul li {
            margin-bottom: 3px;
            line-height: 1.4;
        }
        .info-card-content ul li:last-child {
            margin-bottom: 0;
        }
    </style>
</head>
<body>
    <?php include 'header.php'; ?>
    
    <div class="container-fluid py-4">
        <div class="row">
            <div class="col-12">
                <h4 class="mb-4"><i class="fas fa-mobile-alt mr-2"></i>APP访问管理</h4>
                
                <!-- 生成区域 -->
                <div class="access-card">
                    <h5 class="mb-3"><i class="fas fa-plus-circle mr-2"></i>生成访问授权</h5>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label>授权类型</label>
                            <select class="form-control" id="tokenType">
                                <option value="qrcode">二维码（扫码接管）</option>
                                <option value="key">专属密钥（输入接管）</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>过期时间</label>
                            <select class="form-control" id="expireTime">
                                <option value="0">永不过期</option>
                                <option value="1">1小时</option>
                                <option value="24">1天</option>
                                <option value="168">7天</option>
                                <option value="720">30天</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>使用次数限制</label>
                            <select class="form-control" id="maxUses">
                                <option value="0">无限次</option>
                                <option value="1">1次</option>
                                <option value="5">5次</option>
                                <option value="10">10次</option>
                                <option value="100">100次</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3 d-flex align-items-end">
                            <button class="btn btn-primary btn-generate w-100" onclick="generateToken()">
                                <i class="fas fa-magic mr-2"></i>生成授权
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- 生成结果展示 -->
                <div id="resultArea" class="access-card" style="display: none;">
                    <h5 class="mb-3"><i class="fas fa-check-circle mr-2 text-success"></i>生成成功</h5>
                    <div id="qrcodeResult" style="display: none;">
                        <p class="text-muted mb-3">请使用APP扫描下方二维码接管您的虚拟空间</p>
                        <div class="qrcode-display">
                            <div id="qrcode"></div>
                            <p class="mt-3 mb-0 text-muted" style="font-size: 12px;">二维码包含您的虚拟空间登录信息</p>
                        </div>
                    </div>
                    <div id="keyResult" style="display: none;">
                        <p class="text-muted mb-3">请在APP中输入以下专属密钥</p>
                        <div class="key-display" id="keyText"></div>
                        <button class="btn btn-outline-primary btn-sm mt-3" onclick="copyKey()">
                            <i class="fas fa-copy mr-1"></i>复制密钥
                        </button>
                    </div>
                    <div class="mt-3 p-3 bg-light rounded">
                        <small class="text-muted">
                            <i class="fas fa-info-circle mr-1"></i>
                            <span id="tokenInfo"></span>
                        </small>
                    </div>
                </div>
                
                <!-- 授权列表 -->
                <div class="access-card">
                    <h5 class="mb-3"><i class="fas fa-list mr-2"></i>我的授权列表</h5>
                    <?php if (empty($tokens)): ?>
                        <div class="text-center py-5 text-muted">
                            <i class="fas fa-inbox fa-3x mb-3"></i>
                            <p>暂无授权记录</p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($tokens as $token): 
                            $isExpired = ($token['expire_time'] > 0 && $token['expire_time'] < time()) || 
                                         ($token['max_uses'] > 0 && $token['used_count'] >= $token['max_uses']) ||
                                         $token['status'] == 0;
                            $typeClass = $token['token_type'];
                            $statusClass = $isExpired ? 'expired' : '';
                            
                            // 确认状态
                            $confirmStatus = intval($token['confirm_status']);
                            $confirmBadgeClass = 'secondary';
                            $confirmText = '已确认';
                            if ($confirmStatus === 0) {
                                // 待确认状态，检查是否超时
                                if ($token['confirm_expire_time'] > 0 && $token['confirm_expire_time'] < time()) {
                                    $confirmBadgeClass = 'dark';
                                    $confirmText = '已过期';
                                } else {
                                    $confirmBadgeClass = 'warning';
                                    $confirmText = '待确认';
                                }
                            } elseif ($confirmStatus === 2) {
                                $confirmBadgeClass = 'danger';
                                $confirmText = '已拒绝';
                            }
                        ?>
                            <div class="token-item <?php echo $typeClass; ?> <?php echo $statusClass; ?>">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <span class="badge badge-<?php echo $token['token_type'] == 'qrcode' ? 'success' : 'warning'; ?> mr-2">
                                            <?php echo $token['token_type'] == 'qrcode' ? '二维码' : '密钥'; ?>
                                        </span>
                                        <span class="badge badge-<?php echo $isExpired ? 'danger' : 'info'; ?> mr-2">
                                            <?php echo $isExpired ? '已失效' : '有效'; ?>
                                        </span>
                                        <span class="badge badge-<?php echo $confirmBadgeClass; ?>">
                                            <?php echo $confirmText; ?>
                                        </span>
                                        <div class="mt-2">
                                            <small class="text-muted">
                                                令牌: <?php echo substr($token['token'], 0, 8) . '****' . substr($token['token'], -8); ?>
                                            </small>
                                        </div>
                                        <div class="mt-1">
                                            <small class="text-muted">
                                                <i class="far fa-clock mr-1"></i>
                                                过期: <?php echo $token['expire_time'] > 0 ? date('Y-m-d H:i', $token['expire_time']) : '永不过期'; ?>
                                                <span class="mx-2">|</span>
                                                <i class="fas fa-redo mr-1"></i>
                                                使用: <?php echo $token['used_count']; ?>/<?php echo $token['max_uses'] > 0 ? $token['max_uses'] : '∞'; ?>
                                                <span class="mx-2">|</span>
                                                <i class="far fa-calendar-alt mr-1"></i>
                                                创建: <?php echo date('Y-m-d H:i', $token['create_time']); ?>
                                            </small>
                                        </div>
                                        <?php if ($token['last_use_time'] > 0): ?>
                                            <div class="mt-1">
                                                <small class="text-info">
                                                    <i class="fas fa-sign-in-alt mr-1"></i>
                                                    最后使用: <?php echo date('Y-m-d H:i', $token['last_use_time']); ?>
                                                    (IP: <?php echo $token['last_use_ip']; ?>)
                                                </small>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                    <button class="btn btn-danger btn-sm" onclick="deleteToken(<?php echo $token['id']; ?>)">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                
                <!-- 使用说明 -->
                <div class="access-card">
                    <h5 class="mb-3"><i class="fas fa-question-circle mr-2"></i>使用说明</h5>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <div class="info-card info-card-blue">
                                <div class="info-card-icon"><i class="fas fa-qrcode"></i></div>
                                <div class="info-card-content">
                                    <h6>二维码授权</h6>
                                    <p>生成二维码后，使用APP扫描即可发起绑定请求</p>
                                    <ul>
                                        <li>APP扫码后发起绑定请求</li>
                                        <li>需在网页端确认后完成绑定</li>
                                        <li>确认后APP获得完整管理权限</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <div class="info-card info-card-orange">
                                <div class="info-card-icon"><i class="fas fa-key"></i></div>
                                <div class="info-card-content">
                                    <h6>专属密钥</h6>
                                    <p>生成密钥后，在APP中输入密钥即可发起绑定请求</p>
                                    <ul>
                                        <li>适用于远程授权或分享</li>
                                        <li>APP输入密钥后发起绑定</li>
                                        <li>请妥善保管，不要泄露</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <div class="info-card info-card-green">
                                <div class="info-card-icon"><i class="fas fa-check-circle"></i></div>
                                <div class="info-card-content">
                                    <h6>绑定确认机制</h6>
                                    <p>为了账户安全，所有APP绑定都需要网页端手动确认</p>
                                    <ul>
                                        <li>APP发起请求后显示"待确认"</li>
                                        <li>网页端弹出确认弹窗</li>
                                        <li>有5分钟时间确认或拒绝</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <div class="info-card info-card-red">
                                <div class="info-card-icon"><i class="fas fa-shield-alt"></i></div>
                                <div class="info-card-content">
                                    <h6>安全提示</h6>
                                    <p>授权信息包含虚拟空间完整权限，请谨慎分享</p>
                                    <ul>
                                        <li>建议设置过期时间和次数限制</li>
                                        <li>发现异常请立即删除授权</li>
                                        <li>不要在公共场合展示二维码</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <?php include 'footer.php'; ?>
    
    <!-- QRCode.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
    
    <!-- 绑定确认弹窗 -->
    <div class="modal fade" id="confirmBindModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header bg-warning">
                    <h5 class="modal-title"><i class="fas fa-mobile-alt mr-2"></i>APP绑定确认</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body text-center">
                    <div class="mb-4">
                        <i class="fas fa-question-circle fa-4x text-warning"></i>
                    </div>
                    <h5 class="mb-3">有新的APP绑定请求</h5>
                    <p class="text-muted mb-3">设备信息：<span id="pendingDeviceInfo" class="font-weight-bold text-primary">-</span></p>
                    <p class="text-danger small">
                        <i class="fas fa-exclamation-triangle mr-1"></i>
                        确认后该APP将获得您虚拟空间的完整管理权限
                    </p>
                    <div class="progress mt-3" style="height: 4px;">
                        <div id="confirmProgress" class="progress-bar bg-warning" style="width: 100%"></div>
                    </div>
                    <small class="text-muted">剩余确认时间：<span id="confirmCountdown">300</span>秒</small>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" onclick="rejectBind()">
                        <i class="fas fa-times mr-1"></i>拒绝
                    </button>
                    <button type="button" class="btn btn-success" onclick="confirmBind()">
                        <i class="fas fa-check mr-1"></i>确认绑定
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        let currentToken = '';
        let pendingToken = '';
        let checkInterval = null;
        let countdownInterval = null;
        let countdownTime = 300;
        
        // 生成令牌
        function generateToken() {
            const type = document.getElementById('tokenType').value;
            const expireHours = document.getElementById('expireTime').value;
            const maxUses = document.getElementById('maxUses').value;
            
            // 显示加载状态
            const btn = document.querySelector('.btn-generate');
            const originalText = btn.innerHTML;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>生成中...';
            btn.disabled = true;
            
            fetch('/api/app_api.php?action=generate_token', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: `user_id=<?php echo $user['id']; ?>&type=${type}&expire_hours=${expireHours}&max_uses=${maxUses}`
            })
            .then(res => res.json())
            .then(data => {
                btn.innerHTML = originalText;
                btn.disabled = false;
                
                if (data.code === 200) {
                    currentToken = data.data.token;
                    showResult(data.data);
                } else {
                    alert('生成失败：' + data.msg);
                }
            })
            .catch(err => {
                btn.innerHTML = originalText;
                btn.disabled = false;
                alert('请求失败，请重试');
                console.error(err);
            });
        }
        
        // 显示结果
        function showResult(data) {
            const resultArea = document.getElementById('resultArea');
            const qrcodeResult = document.getElementById('qrcodeResult');
            const keyResult = document.getElementById('keyResult');
            const tokenInfo = document.getElementById('tokenInfo');
            
            resultArea.style.display = 'block';
            
            if (data.type === 'qrcode') {
                qrcodeResult.style.display = 'block';
                keyResult.style.display = 'none';

                // 生成二维码
                document.getElementById('qrcode').innerHTML = '';
                new QRCode(document.getElementById('qrcode'), {
                    text: data.qrcode_data,
                    width: 200,
                    height: 200,
                    colorDark: '#000000',
                    colorLight: '#ffffff',
                    correctLevel: QRCode.CorrectLevel.M
                });
            } else {
                qrcodeResult.style.display = 'none';
                keyResult.style.display = 'block';
                // 使用包含服务器地址的新格式密钥
                const displayKey = data.key_with_url || data.token;
                document.getElementById('keyText').textContent = displayKey;
            }
            
            tokenInfo.innerHTML = `
                授权类型：${data.type === 'qrcode' ? '二维码' : '密钥'} | 
                过期时间：${data.expire_time} | 
                使用限制：${data.max_uses}
            `;
            
            // 滚动到结果区域
            resultArea.scrollIntoView({ behavior: 'smooth' });
        }
        
        // 复制密钥
        function copyKey() {
            const keyText = document.getElementById('keyText').textContent;
            navigator.clipboard.writeText(keyText).then(() => {
                alert('密钥已复制到剪贴板');
            }).catch(() => {
                // 降级方案
                const textarea = document.createElement('textarea');
                textarea.value = keyText;
                document.body.appendChild(textarea);
                textarea.select();
                document.execCommand('copy');
                document.body.removeChild(textarea);
                alert('密钥已复制到剪贴板');
            });
        }
        
        // 删除令牌
        function deleteToken(tokenId) {
            if (!confirm('确定要删除这个授权吗？删除后相关二维码/密钥将失效。')) {
                return;
            }
            
            fetch('/api/app_api.php?action=delete_token', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: `token_id=${tokenId}&user_id=<?php echo $user['id']; ?>`
            })
            .then(res => res.json())
            .then(data => {
                if (data.code === 200) {
                    location.reload();
                } else {
                    alert('删除失败：' + data.msg);
                }
            })
            .catch(() => {
                alert('请求失败，请重试');
            });
        }
        
        // 检查待确认的绑定请求
        function checkPendingBinds() {
            // 如果弹窗已经显示，不再检查
            const modal = document.getElementById('confirmBindModal');
            if (modal && modal.classList.contains('show')) {
                return;
            }
            
            fetch('/api/app_api.php?action=get_pending_binds&user_id=<?php echo $user['id']; ?>')
            .then(res => res.json())
            .then(data => {
                console.log('检查待确认请求:', data);
                if (data.code === 200 && data.data && data.data.length > 0) {
                    // 有待确认的绑定请求
                    const pending = data.data[0];
                    console.log('发现待确认请求:', pending);
                    showConfirmModal(pending);
                }
            })
            .catch(err => {
                console.error('检查待确认请求失败:', err);
            });
        }
        
        // 显示确认弹窗
        function showConfirmModal(pending) {
            const modal = document.getElementById('confirmBindModal');
            // 如果已经有弹窗显示，不再重复显示
            if (modal && modal.classList.contains('show')) {
                return;
            }
            
            pendingToken = pending.token; // 使用完整token
            document.getElementById('pendingDeviceInfo').textContent = pending.device_info || '未知设备';
            
            // 计算剩余时间
            const expireTime = pending.expire_time * 1000;
            const now = Date.now();
            countdownTime = Math.max(0, Math.floor((expireTime - now) / 1000));
            
            updateCountdown();
            
            // 显示弹窗 - 使用Bootstrap的modal方法
            try {
                if (typeof $ !== 'undefined' && $.fn && $.fn.modal) {
                    $('#confirmBindModal').modal({
                        backdrop: 'static',
                        keyboard: false
                    });
                } else {
                    // 降级方案：直接操作CSS
                    modal.style.display = 'block';
                    modal.classList.add('show');
                    document.body.classList.add('modal-open');
                }
            } catch(e) {
                console.error('显示弹窗失败:', e);
                // 降级方案
                modal.style.display = 'block';
                modal.classList.add('show');
                document.body.classList.add('modal-open');
            }
            
            // 启动倒计时
            if (countdownInterval) {
                clearInterval(countdownInterval);
            }
            countdownInterval = setInterval(updateCountdown, 1000);
        }
        
        // 更新倒计时
        function updateCountdown() {
            countdownTime--;
            document.getElementById('confirmCountdown').textContent = countdownTime;
            
            // 更新进度条
            const progress = (countdownTime / 300) * 100;
            document.getElementById('confirmProgress').style.width = progress + '%';
            
            if (countdownTime <= 0) {
                // 超时关闭弹窗
                closeConfirmModal();
                alert('绑定确认已超时');
                location.reload();
            }
        }
        
        // 关闭确认弹窗
        function closeConfirmModal() {
            const modal = document.getElementById('confirmBindModal');
            try {
                if (typeof $ !== 'undefined' && $.fn && $.fn.modal) {
                    $('#confirmBindModal').modal('hide');
                } else {
                    // 降级方案
                    modal.style.display = 'none';
                    modal.classList.remove('show');
                    document.body.classList.remove('modal-open');
                }
            } catch(e) {
                // 降级方案
                modal.style.display = 'none';
                modal.classList.remove('show');
                document.body.classList.remove('modal-open');
            }
            if (countdownInterval) {
                clearInterval(countdownInterval);
                countdownInterval = null;
            }
            pendingToken = '';
        }
        
        // 确认绑定
        function confirmBind() {
            if (!pendingToken) return;
            
            fetch('/api/app_api.php?action=confirm_bind', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: `token=${pendingToken}&user_id=<?php echo $user['id']; ?>&confirm=true`
            })
            .then(res => res.json())
            .then(data => {
                closeConfirmModal();
                if (data.code === 200) {
                    alert('已确认绑定，APP现在可以访问您的虚拟空间');
                    location.reload();
                } else {
                    alert('确认失败：' + data.msg);
                }
            })
            .catch(() => {
                closeConfirmModal();
                alert('请求失败，请重试');
            });
        }
        
        // 拒绝绑定
        function rejectBind() {
            if (!pendingToken) return;
            
            fetch('/api/app_api.php?action=confirm_bind', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: `token=${pendingToken}&user_id=<?php echo $user['id']; ?>&confirm=false`
            })
            .then(res => res.json())
            .then(data => {
                closeConfirmModal();
                if (data.code === 200) {
                    alert('已拒绝绑定请求');
                    location.reload();
                } else {
                    alert('操作失败：' + data.msg);
                }
            })
            .catch(() => {
                closeConfirmModal();
                alert('请求失败，请重试');
            });
        }
        
        // 页面加载完成后启动检查
        document.addEventListener('DOMContentLoaded', function() {
            console.log('APP访问管理页面已加载，启动检查...');
            // 每3秒检查一次待确认的绑定请求
            checkInterval = setInterval(checkPendingBinds, 3000);
            // 立即检查一次
            checkPendingBinds();
            
            // 弹窗关闭后重新启动检查
            try {
                if (typeof $ !== 'undefined' && $.fn && $.fn.modal) {
                    $('#confirmBindModal').on('hidden.bs.modal', function() {
                        pendingToken = '';
                        if (countdownInterval) {
                            clearInterval(countdownInterval);
                            countdownInterval = null;
                        }
                        // 立即检查一次
                        checkPendingBinds();
                    });
                }
            } catch(e) {
                console.log('Bootstrap modal事件监听失败:', e);
            }
        });
        
        // 页面卸载时清理定时器
        window.addEventListener('beforeunload', function() {
            if (checkInterval) {
                clearInterval(checkInterval);
            }
            if (countdownInterval) {
                clearInterval(countdownInterval);
            }
        });
    </script>
</body>
</html>
