<?php
// upload.php (合并版)
session_start();
$upload_id = uniqid();
$_SESSION['upload_id'] = $upload_id;

// --- 后端文件处理逻辑 (处理来自前端的 POST 请求) ---
$uploadDir = '/www/wwwroot/xz.cqshihua.cn/上传的文件/'; // 你的目标路径

// 检查是否是 POST 请求且包含文件
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['fileToUpload'])) {
    // 检查上传过程中是否有错误
    if ($_FILES['fileToUpload']['error'] !== UPLOAD_ERR_OK) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => '文件上传出错，错误代码: ' . $_FILES['fileToUpload']['error']]);
        exit;
    }

    $uploadedFile = $_FILES['fileToUpload'];
    // 构建保存路径
    $fileName = date('Ymd_His_') . basename($uploadedFile['name']);
    $filePath = $uploadDir . $fileName;

    // 移动文件到目标目录
    if (move_uploaded_file($uploadedFile['tmp_name'], $filePath)) {
        echo json_encode(['success' => true, 'message' => '文件上传成功! 保存至上传的文件']);
    } else {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => '无法将文件保存到上传的文件']);
    }
    // 处理完后退出，不渲染前端页面
    exit;
}
// --- 后端逻辑结束 ---
?>

<!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="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        /* ... (你的原始 CSS 样式保持不变) ... */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            width: 100%;
            max-width: 500px;
            padding: 40px;
            position: relative;
            overflow: hidden;
        }

        .container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 5px;
            background: linear-gradient(90deg, #667eea, #764ba2);
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
        }

        .header h1 {
            color: #333;
            font-size: 28px;
            margin-bottom: 10px;
            font-weight: 600;
        }

        .header p {
            color: #666;
            font-size: 16px;
        }

        .upload-area {
            border: 3px dashed #e0e0e0;
            border-radius: 15px;
            padding: 40px 20px;
            text-align: center;
            transition: all 0.3s ease;
            background: #fafafa;
            margin-bottom: 25px;
            cursor: pointer;
            position: relative;
        }

        .upload-area:hover,
        .upload-area.dragover {
            border-color: #667eea;
            background: #f0f4ff;
        }

        .upload-icon {
            font-size: 64px;
            color: #667eea;
            margin-bottom: 15px;
        }

        .upload-text {
            font-size: 18px;
            color: #666;
            margin-bottom: 10px;
        }

        .upload-hint {
            font-size: 14px;
            color: #999;
        }

        .file-input {
            display: none;
        }

        .selected-file {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
            display: none;
        }

        .file-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .file-icon {
            font-size: 24px;
            color: #667eea;
        }

        .file-details {
            flex: 1;
        }

        .file-name {
            font-weight: 500;
            color: #333;
            margin-bottom: 5px;
            word-break: break-all;
        }

        .file-size {
            font-size: 14px;
            color: #666;
        }

        .upload-btn {
            width: 100%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-bottom: 25px;
        }

        .upload-btn:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(102, 126, 234, 0.3);
        }

        .upload-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }

        .progress-container {
            display: none;
            margin-bottom: 25px;
        }

        .progress-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .progress-text {
            font-size: 14px;
            color: #666;
        }

        .progress-bar {
            width: 100%;
            background-color: #f0f0f0;
            border-radius: 10px;
            height: 12px;
            overflow: hidden;
            position: relative;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
            width: 0%;
            transition: width 0.3s ease;
            border-radius: 10px;
            position: relative;
        }

        .progress-fill::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-image: linear-gradient(
                45deg,
                rgba(255,255,255,.2) 25%",
                transparent 25%,
                transparent 50%,
                rgba(255,255,255,.2) 50%,
                rgba(255,255,255,.2) 75%",
                transparent 75%,
                transparent
            );
            background-size: 20px 20px;
            animation: progress-animation 2s linear infinite;
        }

        @keyframes progress-animation {
            0% { background-position: 0 0; }
            100% { background-position: 20px 20px; }
        }

        .speed-display {
            margin-top: 10px;
            font-size: 14px;
            color: #666;
            text-align: center;
        }

        .status-message {
            padding: 15px;
            border-radius: 10px;
            margin-top: 20px;
            display: none;
            text-align: center;
        }

        .success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .cancel-btn {
            background: #dc3545;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s ease;
        }

        .cancel-btn:hover {
            background: #c82333;
        }

        .file-size-limit {
            font-size: 14px;
            color: #666;
            text-align: center;
            margin-top: 10px;
        }

        @media (max-width: 600px) {
            .container {
                margin: 10px;
                padding: 25px;
            }
            
            .header h1 {
                font-size: 24px;
            }
            
            .upload-area {
                padding: 30px 15px;
            }
            
            .upload-icon {
                font-size: 48px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><i class="fas fa-cloud-upload-alt"></i> 文件上传</h1>
            <p>选择您要上传的文件</p>
        </div>

        <div class="upload-area" id="uploadArea">
            <div class="upload-icon">
                <i class="fas fa-file-upload"></i>
            </div>
            <div class="upload-text">点击或拖拽文件到此处</div>
            <div class="upload-hint">支持所有文件类型，无大小限制</div>
            <input type="file" id="fileInput" class="file-input">
        </div>

        <div class="selected-file" id="selectedFile">
            <div class="file-info">
                <div class="file-icon" id="fileIcon">
                    <i class="fas fa-file"></i>
                </div>
                <div class="file-details">
                    <div class="file-name" id="fileName"></div>
                    <div class="file-size" id="fileSize"></div>
                </div>
                <button class="cancel-btn" id="removeFile">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        </div>

        <div class="file-size-limit">
            支持所有文件类型，无大小限制
        </div>

        <button class="upload-btn" id="uploadBtn" disabled>
            <i class="fas fa-upload"></i> 开始上传
        </button>

        <div class="progress-container" id="progressContainer">
            <div class="progress-header">
                <span class="progress-text">上传进度</span>
                <span class="progress-text" id="progressPercent">0%</span>
            </div>
            <div class="progress-bar">
                <div class="progress-fill" id="progressFill"></div>
            </div>
            <div class="speed-display" id="speedDisplay">上传速度：-- KB/s</div>
        </div>

        <div class="status-message" id="statusMessage"></div>
    </div>

    <script>
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');
        const selectedFile = document.getElementById('selectedFile');
        const fileName = document.getElementById('fileName');
        const fileSize = document.getElementById('fileSize');
        const fileIcon = document.getElementById('fileIcon');
        const removeFile = document.getElementById('removeFile');
        const uploadBtn = document.getElementById('uploadBtn');
        const progressContainer = document.getElementById('progressContainer');
        const progressFill = document.getElementById('progressFill');
        const progressPercent = document.getElementById('progressPercent');
        const speedDisplay = document.getElementById('speedDisplay');
        const statusMessage = document.getElementById('statusMessage');

        let selectedFileObj = null;

        uploadArea.addEventListener('click', () => {
            fileInput.click();
        });

        fileInput.addEventListener('change', (e) => {
            if (e.target.files[0]) {
                handleFileSelect(e.target.files[0]);
            }
        });

        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            
            if (e.dataTransfer.files[0]) {
                handleFileSelect(e.dataTransfer.files[0]);
            }
        });

        function handleFileSelect(file) {
            selectedFileObj = file;
            
            fileName.textContent = file.name;
            fileSize.textContent = formatFileSize(file.size);
            
            const ext = file.name.split('.').pop().toLowerCase();
            setFileIcon(ext);
            
            selectedFile.style.display = 'block';
            uploadBtn.disabled = false;
        }

        function setFileIcon(ext) {
            let iconClass = 'fas fa-file';
            
            switch(ext) {
                case 'jpg':
                case 'jpeg':
                case 'png':
                case 'gif':
                    iconClass = 'fas fa-file-image';
                    break;
                case 'pdf':
                    iconClass = 'fas fa-file-pdf';
                    break;
                case 'doc':
                case 'docx':
                    iconClass = 'fas fa-file-word';
                    break;
                case 'xls':
                case 'xlsx':
                    iconClass = 'fas fa-file-excel';
                    break;
                case 'ppt':
                case 'pptx':
                    iconClass = 'fas fa-file-powerpoint';
                    break;
                case 'mp3':
                case 'wav':
                case 'ogg':
                    iconClass = 'fas fa-file-audio';
                    break;
                case 'mp4':
                case 'avi':
                case 'mov':
                    iconClass = 'fas fa-file-video';
                    break;
                case 'zip':
                case 'rar':
                case '7z':
                    iconClass = 'fas fa-file-archive';
                    break;
                case 'txt':
                    iconClass = 'fas fa-file-alt';
                    break;
                case 'exe':
                case 'msi':
                    iconClass = 'fas fa-cogs';
                    break;
                default:
                    iconClass = 'fas fa-file';
            }
            
            fileIcon.innerHTML = `<i class="${iconClass}"></i>`;
        }

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        removeFile.addEventListener('click', () => {
            selectedFileObj = null;
            selectedFile.style.display = 'none';
            fileInput.value = '';
            uploadBtn.disabled = true;
        });

        uploadBtn.addEventListener('click', () => {
            if (!selectedFileObj) return;

            uploadFile(selectedFileObj);
        });

        function uploadFile(file) {
            progressContainer.style.display = 'block';
            statusMessage.style.display = 'none';

            const formData = new FormData();
            formData.append('fileToUpload', file);

            const xhr = new XMLHttpRequest();

            xhr.upload.addEventListener('progress', (e) => {
                if (e.lengthComputable) {
                    const percent = Math.round((e.loaded / e.total) * 100);
                    progressFill.style.width = percent + '%';
                    progressPercent.textContent = percent + '%';
                    
                    calculateSpeed(e.loaded, e.total, xhr);
                }
            });

            xhr.addEventListener('load', () => {
                if (xhr.status === 200) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        if(response.success) {
                            showStatus(response.message || '上传成功！', 'success');
                        } else {
                            showStatus('上传失败：' + (response.error || '未知错误'), 'error');
                        }
                    } catch(e) {
                        // 如果返回的不是JSON格式，当作成功处理
                        showStatus('上传成功！', 'success');
                    }
                    resetForm();
                } else {
                    showStatus('上传失败：' + xhr.statusText, 'error');
                }
            });

            xhr.addEventListener('error', () => {
                showStatus('上传过程中发生错误', 'error');
            });

            // 关键：上传请求发送给自己 (即当前的 upload.php 文件)
            xhr.open('POST', window.location.href, true);
            xhr.setRequestHeader('X-Progress-ID', '<?= $upload_id ?>');
            xhr.send(formData);
        }

        let startTime = null;
        let lastLoaded = 0;

        function calculateSpeed(loaded, total, xhr) {
            if (!startTime) {
                startTime = new Date().getTime();
                lastLoaded = 0;
                return;
            }

            const now = new Date().getTime();
            const timeDiff = (now - startTime) / 1000;
            
            if (timeDiff > 0) {
                const speed = (loaded - lastLoaded) / timeDiff / 1024;
                
                if (speed > 0) {
                    speedDisplay.textContent = `上传速度：${speed.toFixed(2)} KB/s`;
                }
                
                startTime = now;
                lastLoaded = loaded;
            }
        }

        function showStatus(message, type) {
            statusMessage.textContent = message;
            statusMessage.className = 'status-message ' + type;
            statusMessage.style.display = 'block';
        }

        function resetForm() {
            setTimeout(() => {
                selectedFileObj = null;
                selectedFile.style.display = 'none';
                fileInput.value = '';
                uploadBtn.disabled = true;
                progressContainer.style.display = 'none';
                progressFill.style.width = '0%';
                progressPercent.textContent = '0%';
                speedDisplay.textContent = '上传速度：-- KB/s';
                startTime = null;
                lastLoaded = 0;
            }, 2000);
        }
    </script>
</body>
</html>