'use client'; import { useState, useEffect } from 'react'; import { useRouter, useParams } from 'next/navigation'; import BackCircleSvg from '../../svgs/backcirclesvg'; import DownloadIcon from '../../svgs/downloadicon'; import apiService from '../../lib/apiService'; import type { Notice } from '../../admin/notices/mockData'; type Attachment = { name: string; size: string; url?: string; fileKey?: string; }; export default function NoticeDetailPage() { const params = useParams(); const router = useRouter(); const [notice, setNotice] = useState(null); const [attachments, setAttachments] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); // 날짜를 yyyy-mm-dd 형식으로 포맷팅 const formatDate = (dateString: string): string => { if (!dateString) return ''; try { const date = new Date(dateString); if (isNaN(date.getTime())) { // 이미 yyyy-mm-dd 형식인 경우 그대로 반환 if (/^\d{4}-\d{2}-\d{2}$/.test(dateString)) { return dateString; } return dateString; } const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`; } catch { return dateString; } }; useEffect(() => { async function fetchNotice() { if (!params?.id) return; try { setLoading(true); setError(null); const noticeId = Array.isArray(params.id) ? params.id[0] : params.id; const response = await apiService.getNotice(noticeId); const data = response.data; // API 응답 데이터를 Notice 형식으로 변환 const transformedNotice: Notice = { id: data.id || data.noticeId || Number(params.id), title: data.title || '', date: formatDate(data.date || data.createdAt || data.createdDate || new Date().toISOString().split('T')[0]), views: data.views || data.viewCount || 0, writer: data.writer || data.author || data.createdBy || '관리자', content: data.content ? (Array.isArray(data.content) ? data.content : typeof data.content === 'string' ? data.content.split('\n').filter((line: string) => line.trim()) : [String(data.content)]) : [], hasAttachment: data.hasAttachment || data.attachment || false, }; // 첨부파일 정보 처리 if (data.attachments && Array.isArray(data.attachments)) { setAttachments(data.attachments.map((att: any) => ({ name: att.name || att.fileName || att.filename || '', size: att.size || att.fileSize || '', url: att.url || att.downloadUrl, fileKey: att.fileKey || att.key || att.fileId, }))); } else if (transformedNotice.hasAttachment && data.attachment) { // 단일 첨부파일인 경우 setAttachments([{ name: data.attachment.name || data.attachment.fileName || data.attachment.filename || '첨부파일', size: data.attachment.size || data.attachment.fileSize || '', url: data.attachment.url || data.attachment.downloadUrl, fileKey: data.attachment.fileKey || data.attachment.key || data.attachment.fileId, }]); } if (!transformedNotice.title) { setError('공지사항을 찾을 수 없습니다.'); return; } setNotice(transformedNotice); } catch (err) { console.error('공지사항 조회 오류:', err); setError('공지사항을 불러오는 중 오류가 발생했습니다.'); } finally { setLoading(false); } } fetchNotice(); }, [params?.id]); const handleDownload = async (fileKey?: string, url?: string, fileName?: string) => { if (url) { // URL이 있으면 직접 다운로드 const link = document.createElement('a'); link.href = url; link.download = fileName || 'download'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } else if (fileKey) { // fileKey가 있으면 API를 통해 다운로드 try { const fileUrl = await apiService.getFile(fileKey); if (fileUrl) { const link = document.createElement('a'); link.href = fileUrl; link.download = fileName || 'download'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } } catch (error) { console.error('파일 다운로드 오류:', error); alert('파일 다운로드 중 오류가 발생했습니다.'); } } }; if (loading) { return (

로딩 중...

); } if (error || !notice) { return (

{error || '공지사항을 찾을 수 없습니다.'}

); } return (
{/* 상단 타이틀 */}

공지사항 상세

{/* 카드 */}
{/* 헤더 */}

{notice.title}

작성자 {notice.writer} 게시일 {notice.date} 조회수 {notice.views.toLocaleString()}
{/* 구분선 */}
{/* 본문 */}
{notice.content && notice.content.length > 0 ? ( notice.content.map((p, idx) => (

{p}

)) ) : (

내용이 없습니다.

)}
{/* 첨부파일 섹션 */} {attachments.length > 0 && (
첨부 파일
{attachments.map((attachment, idx) => (

{attachment.name}

{attachment.size}

))}
)}
); }