import React, { useCallback, useState } from 'react';
import * as tus from 'tus-js-client';

const UploadTest: React.FC = () => {
    const [progress, setProgress] = useState<number>(0);
    const [uploadStatus, setUploadStatus] = useState<string>('');

    const handleFileSelect = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
        const file = event.target.files?.[0];
        if (!file) return;

        // 创建 tus upload 实例
        const upload = new tus.Upload(file, {
            endpoint: 'http://localhost:8080/files', // 替换成你的 NestJS 服务器地址
            retryDelays: [0, 3000, 5000],
            metadata: {
                filename: file.name,
                filetype: file.type
            },
            onError: (error) => {
                console.error('上传失败:', error);
                setUploadStatus('上传失败');
            },
            onProgress: (bytesUploaded, bytesTotal) => {
                const percentage = ((bytesUploaded / bytesTotal) * 100).toFixed(2);
                setProgress(Number(percentage));
                setUploadStatus('上传中...');
            },
            onSuccess: () => {
                setUploadStatus('上传成功！');
                console.log('上传完成:', upload.url);
            }
        });

        // 开始上传
        upload.start();
    }, []);

    return (
        <div style={{ padding: '20px' }}>
            <h2>文件上传测试</h2>
            <input
                type="file"
                onChange={handleFileSelect}
                style={{ marginBottom: '20px' }}
            />

            {progress > 0 && (
                <div>
                    <div>上传进度: {progress}%</div>
                    <div style={{
                        width: '300px',
                        height: '20px',
                        border: '1px solid #ccc',
                        marginTop: '10px'
                    }}>
                        <div style={{
                            width: `${progress}%`,
                            height: '100%',
                            backgroundColor: '#4CAF50',
                            transition: 'width 0.3s'
                        }} />
                    </div>
                </div>
            )}

            {uploadStatus && (
                <div style={{ marginTop: '10px' }}>
                    状态: {uploadStatus}
                </div>
            )}
        </div>
    );
};


export default function HomePage() {
    return <UploadTest></UploadTest>
}