import { NextRequest, NextResponse } from 'next/server' import { getDb } from '@/lib/db' import { initDatabase } from '@/lib/db-schema' import { getCurrentUser } from '@/lib/auth' import { hasPermission } from '@/lib/permissions' import JSZip from 'jszip' import fs from 'fs' export async function POST(request: NextRequest) { try { initDatabase() const user = await getCurrentUser() if (!user) return NextResponse.json({ error: '未登录' }, { status: 401 }) if (!hasPermission(user, 'reports:download')) return NextResponse.json({ error: '权限不足' }, { status: 403 }) const { ids } = await request.json() if (!Array.isArray(ids) || ids.length === 0) { return NextResponse.json({ error: '缺少 ids 参数' }, { status: 400 }) } const db = getDb() const reports = db.prepare( `SELECT * FROM reports WHERE id IN (${ids.map(() => '?').join(',')})` ).all(...ids) as any[] if (reports.length === 0) { return NextResponse.json({ error: '未找到选中的报告' }, { status: 404 }) } const zip = new JSZip() for (const r of reports) { if (r.status === 'completed' && r.file_path && fs.existsSync(r.file_path)) { const buffer = fs.readFileSync(r.file_path) const fileName = r.file_name || `report_${r.id}.docx` zip.file(fileName, buffer) } } if (Object.keys(zip.files).length === 0) { return NextResponse.json({ error: '没有可下载的报告文件' }, { status: 400 }) } const zipBuffer = await zip.generateAsync({ type: 'nodebuffer' }) const downloadName = `reports_${new Date().toISOString().slice(0, 10)}.zip` const encodedName = encodeURIComponent(downloadName) return new NextResponse(new Uint8Array(zipBuffer), { headers: { 'Content-Type': 'application/zip', 'Content-Disposition': `attachment; filename*=UTF-8''${encodedName}`, }, }) } catch (e) { const msg = e instanceof Error ? e.message : '批量下载失败' return NextResponse.json({ error: msg }, { status: 500 }) } }