// 配置
const ADMIN_PASSWORD = 'admin123'; // 管理员密码
const API_BASE_URL = 'http://localhost:6902/api'; // 后端API基础URL

// 初始化
function init() {
    checkLoginStatus();
    loadAppList();
}

// 检查登录状态
function checkLoginStatus() {
    const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
    if (isLoggedIn) {
        showUploadSection();
    }
}

// 登录功能
function login() {
    const password = document.getElementById('password').value;
    const message = document.getElementById('loginMessage');
    
    if (password === ADMIN_PASSWORD) {
        localStorage.setItem('isLoggedIn', 'true');
        showUploadSection();
        message.textContent = '登录成功！';
        message.style.color = '#0000ff';
        document.getElementById('password').value = '';
    } else {
        message.textContent = '密码错误，请重试！';
        message.style.color = '#ff0000';
    }
}

// 显示上传区域
function showUploadSection() {
    document.getElementById('loginSection').style.display = 'none';
    document.getElementById('uploadSection').style.display = 'block';
    const loginSection = document.getElementById('loginSection');
    const logoutBtn = document.createElement('button');
    logoutBtn.textContent = '退出登录';
    logoutBtn.className = 'logout-btn';
    logoutBtn.onclick = logout;
    loginSection.appendChild(logoutBtn);
}

// 退出登录
function logout() {
    localStorage.removeItem('isLoggedIn');
    location.reload();
}

// 加载App列表
function loadAppList() {
    const appList = document.getElementById('appList');
    
    fetch(`${API_BASE_URL}/apps`)
        .then(response => response.json())
        .then(apps => {
            if (apps.length === 0) {
                appList.innerHTML = '<p style="text-align: center;">暂无App</p>';
                return;
            }
            
            appList.innerHTML = '';
            apps.forEach(app => {
                const appItem = document.createElement('div');
                appItem.className = 'app-item';
                
                const appInfo = document.createElement('div');
                appInfo.className = 'app-info';
                
                const appName = document.createElement('h3');
                appName.textContent = app.name;
                
                const appDate = document.createElement('p');
                appDate.textContent = `上传时间：${app.date}`;
                
                const downloadBtn = document.createElement('button');
                downloadBtn.className = 'download-btn';
                downloadBtn.textContent = '下载';
                downloadBtn.onclick = () => downloadApp(app.id, app.fileName);
                
                const copyLinkBtn = document.createElement('button');
                copyLinkBtn.className = 'download-btn';
                copyLinkBtn.textContent = '复制直链';
                copyLinkBtn.onclick = () => copyDirectLink(app.id, app.fileName);
                
                appInfo.appendChild(appName);
                appInfo.appendChild(appDate);
                appItem.appendChild(appInfo);
                
                const buttonsContainer = document.createElement('div');
                buttonsContainer.style.display = 'flex';
                buttonsContainer.style.gap = '10px';
                buttonsContainer.appendChild(downloadBtn);
                buttonsContainer.appendChild(copyLinkBtn);
                
                appItem.appendChild(buttonsContainer);
                appList.appendChild(appItem);
            });
        })
        .catch(error => {
            console.error('获取App列表失败:', error);
            appList.innerHTML = '<p style="color: #ff0000; text-align: center;">获取App列表失败</p>';
        });
}

// 上传App
function uploadApp() {
    let appName = document.getElementById('appName').value;
    const appFile = document.getElementById('appFile').files[0];
    const message = document.getElementById('uploadMessage');
    
    if (!appFile) {
        message.textContent = '请选择文件！';
        message.style.color = '#ff0000';
        return;
    }
    
    if (appFile.size > 100 * 1024 * 1024) { // 限制100MB
        message.textContent = '文件大小不能超过100MB！';
        message.style.color = '#ff0000';
        return;
    }
    
    // 如果App名称为空，使用文件名作为默认值
    if (!appName.trim()) {
        // 去除文件扩展名
        appName = appFile.name.replace(/\.[^/.]+$/, '');
    }
    
    const formData = new FormData();
    formData.append('name', appName);
    formData.append('file', appFile);
    
    fetch(`${API_BASE_URL}/apps`, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            message.textContent = '上传成功！';
            message.style.color = '#0000ff';
            loadAppList();
            // 清空表单
            document.getElementById('appName').value = '';
            document.getElementById('appFile').value = '';
        } else {
            message.textContent = '上传失败：' + (result.message || '未知错误');
            message.style.color = '#ff0000';
        }
    })
    .catch(error => {
        console.error('上传失败:', error);
        message.textContent = '上传失败，请重试！';
        message.style.color = '#ff0000';
    });
}

// 下载App
function downloadApp(appId, fileName) {
    const link = document.createElement('a');
    link.href = `${API_BASE_URL}/apps/${appId}`;
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// 复制直链
function copyDirectLink(appId, fileName) {
    const directLink = `${API_BASE_URL}/apps/${appId}`;
    
    // 复制到剪贴板
    navigator.clipboard.writeText(directLink)
        .then(() => {
            // 显示复制成功提示
            const message = document.createElement('div');
            message.textContent = '直链已复制到剪贴板！';
            message.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background-color: #000;
                color: #fff;
                padding: 10px 20px;
                border-radius: 5px;
                font-size: 14px;
                z-index: 1000;
            `;
            
            document.body.appendChild(message);
            
            // 3秒后移除提示
            setTimeout(() => {
                document.body.removeChild(message);
            }, 3000);
        })
        .catch(err => {
            console.error('复制失败:', err);
        });
}

// 页面加载完成后初始化
window.onload = init;