import { useState, useRef, useEffect } from 'react' import { Upload, FileSpreadsheet, CheckCircle, AlertCircle, Download, Trash2 } from 'lucide-react' import api from '../../api' import toast from 'react-hot-toast' const SECTIONS = [ { key: 'accident', label: '意外 Accident', color: 'red' }, { key: 'attendance', label: '出勤 Attendance', color: 'blue' }, ] export default function UploadPage() { const [section, setSection] = useState('accident') const [file, setFile] = useState(null) const [uploading, setUploading] = useState(false) const [result, setResult] = useState(null) const [info, setInfo] = useState(null) const fileInputRef = useRef() const [uploadProgress, setUploadProgress] = useState(0) const currentSection = SECTIONS.find(s => s.key === section) // Load current file info when section changes useEffect(() => { loadSectionInfo() }, [section]) async function loadSectionInfo() { try { const { data } = await api.get(`/api/${section}/info`) setInfo(data) } catch (err) { console.error(err) } } async function handleClear() { if (!confirm(`確定要刪除 ${section} 的所有數據嗎?這個操作無法撤銷!`)) return try { await api.delete(`/api/upload/${section}`) toast.success(`${section} 數據已清除`) setInfo({ uploaded: false, rows: 0, columns: 0, headers: [] }) } catch (err) { toast.error(err.response?.data?.detail || '清除失敗') } } function handleFileChange(e) { const f = e.target.files[0] if (f) { setFile(f) setResult(null) } } async function handleUpload() { if (!file) return setUploading(true) setResult(null) setUploadProgress(0) try { const formData = new FormData() formData.append('file', file) // Simulate progress const progressInterval = setInterval(() => { setUploadProgress(p => Math.min(p + 10, 90)) }, 200) const { data } = await api.post(`/api/upload/${section}`, formData, { headers: { 'Content-Type': 'multipart/form-data' }, onUploadProgress: (e) => { if (e.total) setUploadProgress(Math.round((e.loaded * 100) / e.total)) } }) clearInterval(progressInterval) setUploadProgress(100) setResult(data) toast.success(`${section === 'accident' ? '意外' : '出勤'} 數據上傳成功!`) setFile(null) loadSectionInfo() } catch (err) { toast.error(err.response?.data?.detail || '上傳失敗') setUploadProgress(0) } finally { setUploading(false) } } function handleCancelUpload() { // Cancel is handled by just resetting the state setUploading(false) setUploadProgress(0) setFile(null) toast.success('已取消上傳') } async function handleDownload() { try { const { data: tokenData } = await api.post('/api/auth/login', { email: 'admin@aars.hk', password: 'Admin@1234' }) const token = tokenData.access_token window.location.href = `https://excel.donton.cloud/api/export/${section}/excel?token=${token}` } catch (err) { toast.error('Download failed') } } return (
直接上傳 Excel 檔案作為數據源
{file ? file.name : '點擊選擇 Excel 檔案'}
支援 .xlsx, .xls 格式