1852 lines
87 KiB
TypeScript
1852 lines
87 KiB
TypeScript
'use client';
|
|
|
|
import { useState, useMemo, useRef, useEffect, useCallback } from "react";
|
|
import { useRouter, useSearchParams } from "next/navigation";
|
|
import AdminSidebar from "@/app/components/AdminSidebar";
|
|
import ChevronDownSvg from "@/app/svgs/chevrondownsvg";
|
|
import DropdownIcon from "@/app/svgs/dropdownicon";
|
|
import BackArrowSvg from "@/app/svgs/backarrow";
|
|
import { getCourses, type Course } from "@/app/admin/courses/mockData";
|
|
import CloseXOSvg from "@/app/svgs/closexo";
|
|
import apiService from "@/app/lib/apiService";
|
|
|
|
type Lesson = {
|
|
id: string;
|
|
courseName: string; // 교육과정명
|
|
lessonName: string; // 강좌명
|
|
attachments: string; // 첨부파일 (예: "강좌영상 3개, VR콘텐츠 2개, 평가문제 1개")
|
|
questionCount: number; // 학습 평가 문제 수
|
|
createdBy: string; // 등록자
|
|
createdAt: string; // 등록일
|
|
};
|
|
|
|
export default function AdminLessonsPage() {
|
|
const router = useRouter();
|
|
const searchParams = useSearchParams();
|
|
const [lessons, setLessons] = useState<Lesson[]>([]);
|
|
const [currentPage, setCurrentPage] = useState(1);
|
|
const [isRegistrationMode, setIsRegistrationMode] = useState(false);
|
|
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
|
|
const dropdownRef = useRef<HTMLDivElement>(null);
|
|
const [courses, setCourses] = useState<Course[]>([]);
|
|
const [currentUser, setCurrentUser] = useState<string>("관리자");
|
|
const [showToast, setShowToast] = useState(false);
|
|
const [toastMessage, setToastMessage] = useState<string>('강좌가 등록되었습니다.');
|
|
const rawLecturesRef = useRef<any[]>([]); // 원본 강좌 데이터 저장
|
|
|
|
// 등록 폼 상태
|
|
const [selectedCourse, setSelectedCourse] = useState<string>("");
|
|
const [lessonName, setLessonName] = useState("");
|
|
const [learningGoal, setLearningGoal] = useState("");
|
|
const [courseVideoCount, setCourseVideoCount] = useState(0);
|
|
const [courseVideoFiles, setCourseVideoFiles] = useState<string[]>([]);
|
|
const [courseVideoFileObjects, setCourseVideoFileObjects] = useState<File[]>([]);
|
|
const [courseVideoFileKeys, setCourseVideoFileKeys] = useState<string[]>([]);
|
|
const [vrContentCount, setVrContentCount] = useState(0);
|
|
const [vrContentFiles, setVrContentFiles] = useState<string[]>([]);
|
|
const [vrContentFileObjects, setVrContentFileObjects] = useState<File[]>([]);
|
|
const [vrContentFileKeys, setVrContentFileKeys] = useState<string[]>([]);
|
|
const [questionFileCount, setQuestionFileCount] = useState(0);
|
|
const [questionFileObject, setQuestionFileObject] = useState<File | null>(null);
|
|
const [questionFileKey, setQuestionFileKey] = useState<string | null>(null);
|
|
const [csvData, setCsvData] = useState<string[][]>([]);
|
|
const [csvHeaders, setCsvHeaders] = useState<string[]>([]);
|
|
const [csvRows, setCsvRows] = useState<string[][]>([]);
|
|
|
|
// 파일 교체 확인 모달 상태
|
|
const [isFileReplaceModalOpen, setIsFileReplaceModalOpen] = useState(false);
|
|
const [pendingFiles, setPendingFiles] = useState<File[]>([]);
|
|
const [pendingFileType, setPendingFileType] = useState<'video' | 'vr' | 'csv' | null>(null);
|
|
|
|
// 에러 상태
|
|
const [errors, setErrors] = useState<{
|
|
selectedCourse?: string;
|
|
lessonName?: string;
|
|
learningGoal?: string;
|
|
}>({});
|
|
|
|
// CSV 파싱 함수
|
|
const parseCsv = (csvText: string): string[][] => {
|
|
const lines: string[][] = [];
|
|
let currentLine: string[] = [];
|
|
let currentField = '';
|
|
let inQuotes = false;
|
|
|
|
for (let i = 0; i < csvText.length; i++) {
|
|
const char = csvText[i];
|
|
const nextChar = csvText[i + 1];
|
|
|
|
if (char === '"') {
|
|
if (inQuotes && nextChar === '"') {
|
|
currentField += '"';
|
|
i++;
|
|
} else {
|
|
inQuotes = !inQuotes;
|
|
}
|
|
} else if (char === ',' && !inQuotes) {
|
|
currentLine.push(currentField.trim());
|
|
currentField = '';
|
|
} else if ((char === '\n' || char === '\r') && !inQuotes) {
|
|
if (char === '\r' && nextChar === '\n') {
|
|
i++;
|
|
}
|
|
if (currentField || currentLine.length > 0) {
|
|
currentLine.push(currentField.trim());
|
|
lines.push(currentLine);
|
|
currentLine = [];
|
|
currentField = '';
|
|
}
|
|
} else {
|
|
currentField += char;
|
|
}
|
|
}
|
|
|
|
if (currentField || currentLine.length > 0) {
|
|
currentLine.push(currentField.trim());
|
|
lines.push(currentLine);
|
|
}
|
|
|
|
return lines;
|
|
};
|
|
|
|
// CSV 파일에서 행 개수 가져오기
|
|
const getCsvRowCount = async (lecture: any): Promise<number> => {
|
|
if (!lecture.csvUrl && !lecture.csvKey) {
|
|
return 0;
|
|
}
|
|
|
|
try {
|
|
const baseURL = process.env.NEXT_PUBLIC_API_BASE_URL || 'https://hrdi.coconutmeet.net';
|
|
const token = typeof window !== 'undefined' ? localStorage.getItem('token') : null;
|
|
|
|
let fileKey: string | null = null;
|
|
|
|
// csvUrl에서 fileKey 추출
|
|
if (lecture.csvUrl) {
|
|
// 전체 URL인 경우 fileKey 추출
|
|
if (lecture.csvUrl.startsWith('http://') || lecture.csvUrl.startsWith('https://')) {
|
|
// URL에서 /api/files/ 이후 부분을 fileKey로 사용
|
|
const filesIndex = lecture.csvUrl.indexOf('/api/files/');
|
|
if (filesIndex !== -1) {
|
|
fileKey = lecture.csvUrl.substring(filesIndex + '/api/files/'.length);
|
|
// URL 디코딩
|
|
fileKey = decodeURIComponent(fileKey);
|
|
} else {
|
|
// URL에서 마지막 경로를 fileKey로 사용
|
|
const urlParts = lecture.csvUrl.split('/');
|
|
fileKey = urlParts[urlParts.length - 1];
|
|
fileKey = decodeURIComponent(fileKey);
|
|
}
|
|
} else if (lecture.csvUrl.startsWith('csv/')) {
|
|
// "csv/" 접두사 제거
|
|
fileKey = lecture.csvUrl.substring(4);
|
|
} else {
|
|
// 그 외의 경우 fileKey로 사용
|
|
fileKey = lecture.csvUrl;
|
|
}
|
|
} else if (lecture.csvKey) {
|
|
// csvKey가 있으면 fileKey로 사용
|
|
fileKey = lecture.csvKey;
|
|
}
|
|
|
|
if (!fileKey) {
|
|
return 0;
|
|
}
|
|
|
|
// /api/files/{fileKey} 형태로 요청
|
|
const csvUrl = `${baseURL}/api/files/${encodeURIComponent(fileKey)}`;
|
|
|
|
const csvResponse = await fetch(csvUrl, {
|
|
method: 'GET',
|
|
headers: {
|
|
...(token && { Authorization: `Bearer ${token}` }),
|
|
},
|
|
});
|
|
|
|
if (csvResponse.ok) {
|
|
const csvText = await csvResponse.text();
|
|
const parsed = parseCsv(csvText);
|
|
// 헤더를 제외한 행 개수 반환
|
|
return parsed.length > 0 ? parsed.length - 1 : 0;
|
|
} else {
|
|
console.warn(`CSV 파일 다운로드 실패: ${csvResponse.status} - ${csvUrl}`);
|
|
return 0;
|
|
}
|
|
} catch (error) {
|
|
console.error('CSV 파일 파싱 실패:', error, lecture);
|
|
return 0;
|
|
}
|
|
};
|
|
|
|
// 교육과정명 매핑 함수
|
|
const mapCourseNames = useCallback(async (lectures: any[]) => {
|
|
// 먼저 기본 정보로 강좌 목록 생성
|
|
const initialLessons: Lesson[] = lectures.map((lecture: any) => {
|
|
// 첨부파일 정보 구성
|
|
const attachmentParts: string[] = [];
|
|
|
|
// 강좌 영상 개수 계산
|
|
if (lecture.videoUrl) {
|
|
if (Array.isArray(lecture.videoUrl)) {
|
|
const count = lecture.videoUrl.length;
|
|
if (count > 0) {
|
|
attachmentParts.push(`강좌영상 ${count}개`);
|
|
}
|
|
} else if (typeof lecture.videoUrl === 'string') {
|
|
attachmentParts.push('강좌영상 1개');
|
|
}
|
|
} else if (lecture.videoKeys && Array.isArray(lecture.videoKeys)) {
|
|
const count = lecture.videoKeys.length;
|
|
if (count > 0) {
|
|
attachmentParts.push(`강좌영상 ${count}개`);
|
|
}
|
|
} else if (lecture.videoFileKeys && Array.isArray(lecture.videoFileKeys)) {
|
|
const count = lecture.videoFileKeys.length;
|
|
if (count > 0) {
|
|
attachmentParts.push(`강좌영상 ${count}개`);
|
|
}
|
|
} else if (lecture.videoFiles && Array.isArray(lecture.videoFiles)) {
|
|
const count = lecture.videoFiles.length;
|
|
if (count > 0) {
|
|
attachmentParts.push(`강좌영상 ${count}개`);
|
|
}
|
|
} else if (lecture.videoKey) {
|
|
attachmentParts.push('강좌영상 1개');
|
|
}
|
|
|
|
// VR 콘텐츠 개수 계산
|
|
if (lecture.webglUrl) {
|
|
if (Array.isArray(lecture.webglUrl)) {
|
|
const count = lecture.webglUrl.length;
|
|
if (count > 0) {
|
|
attachmentParts.push(`VR콘텐츠 ${count}개`);
|
|
}
|
|
} else if (typeof lecture.webglUrl === 'string') {
|
|
attachmentParts.push('VR콘텐츠 1개');
|
|
}
|
|
} else if (lecture.vrUrl) {
|
|
if (Array.isArray(lecture.vrUrl)) {
|
|
const count = lecture.vrUrl.length;
|
|
if (count > 0) {
|
|
attachmentParts.push(`VR콘텐츠 ${count}개`);
|
|
}
|
|
} else if (typeof lecture.vrUrl === 'string') {
|
|
attachmentParts.push('VR콘텐츠 1개');
|
|
}
|
|
} else if (lecture.webglKeys && Array.isArray(lecture.webglKeys)) {
|
|
const count = lecture.webglKeys.length;
|
|
if (count > 0) {
|
|
attachmentParts.push(`VR콘텐츠 ${count}개`);
|
|
}
|
|
} else if (lecture.vrKeys && Array.isArray(lecture.vrKeys)) {
|
|
const count = lecture.vrKeys.length;
|
|
if (count > 0) {
|
|
attachmentParts.push(`VR콘텐츠 ${count}개`);
|
|
}
|
|
} else if (lecture.webglFileKeys && Array.isArray(lecture.webglFileKeys)) {
|
|
const count = lecture.webglFileKeys.length;
|
|
if (count > 0) {
|
|
attachmentParts.push(`VR콘텐츠 ${count}개`);
|
|
}
|
|
} else if (lecture.vrFileKeys && Array.isArray(lecture.vrFileKeys)) {
|
|
const count = lecture.vrFileKeys.length;
|
|
if (count > 0) {
|
|
attachmentParts.push(`VR콘텐츠 ${count}개`);
|
|
}
|
|
} else if (lecture.webglFiles && Array.isArray(lecture.webglFiles)) {
|
|
const count = lecture.webglFiles.length;
|
|
if (count > 0) {
|
|
attachmentParts.push(`VR콘텐츠 ${count}개`);
|
|
}
|
|
} else if (lecture.webglKey || lecture.vrKey) {
|
|
attachmentParts.push('VR콘텐츠 1개');
|
|
}
|
|
|
|
// 학습 평가 문제 개수는 나중에 업데이트
|
|
// csvUrl이 전체 URL이든 상대 경로든 모두 체크
|
|
if (lecture.csvUrl || lecture.csvKey) {
|
|
attachmentParts.push('평가문제 확인 중...');
|
|
}
|
|
|
|
const attachments = attachmentParts.length > 0
|
|
? attachmentParts.join(', ')
|
|
: '없음';
|
|
|
|
// subjectId로 교육과정명 찾기
|
|
const subjectId = lecture.subjectId || lecture.subject_id;
|
|
let courseName = '';
|
|
if (subjectId && courses.length > 0) {
|
|
const foundCourse = courses.find(course => course.id === String(subjectId));
|
|
courseName = foundCourse?.courseName || '';
|
|
}
|
|
|
|
// 교육과정명을 찾지 못한 경우 fallback
|
|
if (!courseName) {
|
|
courseName = lecture.subjectName || lecture.courseName || '';
|
|
}
|
|
|
|
return {
|
|
id: String(lecture.id || lecture.lectureId || ''),
|
|
courseName,
|
|
lessonName: lecture.title || lecture.lessonName || '',
|
|
attachments,
|
|
questionCount: 0, // 초기값은 0, 나중에 업데이트
|
|
createdBy: lecture.createdBy || lecture.instructorName || '관리자',
|
|
createdAt: lecture.createdAt
|
|
? new Date(lecture.createdAt).toISOString().split('T')[0]
|
|
: new Date().toISOString().split('T')[0],
|
|
};
|
|
});
|
|
|
|
// 초기 목록 설정
|
|
setLessons(initialLessons);
|
|
|
|
// CSV 파일 행 개수 병렬로 가져오기
|
|
const csvRowCounts = await Promise.all(
|
|
lectures.map(lecture => getCsvRowCount(lecture))
|
|
);
|
|
|
|
// CSV 행 개수로 업데이트
|
|
const updatedLessons = initialLessons.map((lesson, index) => {
|
|
const lecture = lectures[index];
|
|
const rowCount = csvRowCounts[index];
|
|
|
|
// 첨부파일 정보 업데이트
|
|
let attachments = lesson.attachments;
|
|
if (lecture.csvUrl || lecture.csvKey) {
|
|
if (rowCount > 0) {
|
|
attachments = attachments.replace('평가문제 확인 중...', `평가문제 ${rowCount}개`);
|
|
} else {
|
|
// CSV 파일이 있지만 다운로드 실패하거나 행이 없는 경우에도 표시
|
|
attachments = attachments.replace('평가문제 확인 중...', '평가문제 1개');
|
|
}
|
|
}
|
|
|
|
return {
|
|
...lesson,
|
|
attachments,
|
|
questionCount: rowCount,
|
|
};
|
|
});
|
|
|
|
setLessons(updatedLessons);
|
|
}, [courses]);
|
|
|
|
// 교육과정 목록 가져오기
|
|
useEffect(() => {
|
|
async function fetchCourses() {
|
|
try {
|
|
const data = await getCourses();
|
|
setCourses(data);
|
|
} catch (error) {
|
|
console.error('교육과정 목록 로드 오류:', error);
|
|
setCourses([]);
|
|
}
|
|
}
|
|
fetchCourses();
|
|
}, []);
|
|
|
|
// 강좌 리스트 조회 함수
|
|
const fetchLectures = useCallback(async () => {
|
|
try {
|
|
const response = await apiService.getLectures();
|
|
if (response.data && Array.isArray(response.data)) {
|
|
// 원본 데이터 저장
|
|
rawLecturesRef.current = response.data;
|
|
// 교육과정명 매핑 함수 호출
|
|
await mapCourseNames(response.data);
|
|
}
|
|
} catch (error) {
|
|
console.error('강좌 리스트 조회 오류:', error);
|
|
setLessons([]);
|
|
rawLecturesRef.current = [];
|
|
}
|
|
}, [mapCourseNames]);
|
|
|
|
// 강좌 리스트 조회
|
|
useEffect(() => {
|
|
fetchLectures();
|
|
}, [fetchLectures]);
|
|
|
|
// 페이지 포커스 및 가시성 변경 시 리스트 새로고침
|
|
useEffect(() => {
|
|
const handleFocus = () => {
|
|
fetchLectures();
|
|
};
|
|
|
|
const handleVisibilityChange = () => {
|
|
if (!document.hidden) {
|
|
fetchLectures();
|
|
}
|
|
};
|
|
|
|
window.addEventListener('focus', handleFocus);
|
|
document.addEventListener('visibilitychange', handleVisibilityChange);
|
|
|
|
return () => {
|
|
window.removeEventListener('focus', handleFocus);
|
|
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
|
};
|
|
}, [fetchLectures]);
|
|
|
|
// 교육과정 목록이 로드되면 강좌 리스트의 교육과정명 업데이트
|
|
useEffect(() => {
|
|
const updateLectures = async () => {
|
|
if (rawLecturesRef.current.length > 0) {
|
|
await mapCourseNames(rawLecturesRef.current);
|
|
}
|
|
};
|
|
updateLectures();
|
|
}, [mapCourseNames]);
|
|
|
|
// 현재 사용자 정보 가져오기
|
|
useEffect(() => {
|
|
async function fetchCurrentUser() {
|
|
try {
|
|
const token = typeof window !== 'undefined'
|
|
? (localStorage.getItem('token') || document.cookie
|
|
.split('; ')
|
|
.find(row => row.startsWith('token='))
|
|
?.split('=')[1])
|
|
: null;
|
|
|
|
if (!token) {
|
|
return;
|
|
}
|
|
|
|
const response = await apiService.getCurrentUser();
|
|
|
|
if (response.data && response.data.name) {
|
|
setCurrentUser(response.data.name);
|
|
}
|
|
} catch (error) {
|
|
console.error('사용자 정보 조회 오류:', error);
|
|
}
|
|
}
|
|
fetchCurrentUser();
|
|
}, []);
|
|
|
|
const totalCount = useMemo(() => lessons.length, [lessons]);
|
|
|
|
const ITEMS_PER_PAGE = 10;
|
|
const sortedLessons = useMemo(() => {
|
|
return [...lessons].sort((a, b) => {
|
|
// 생성일 내림차순 정렬 (최신 날짜가 먼저)
|
|
return b.createdAt.localeCompare(a.createdAt);
|
|
});
|
|
}, [lessons]);
|
|
|
|
const totalPages = Math.ceil(sortedLessons.length / ITEMS_PER_PAGE);
|
|
const paginatedLessons = useMemo(() => {
|
|
const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
|
|
const endIndex = startIndex + ITEMS_PER_PAGE;
|
|
return sortedLessons.slice(startIndex, endIndex);
|
|
}, [sortedLessons, currentPage]);
|
|
|
|
// 교육과정 옵션
|
|
const courseOptions = useMemo(() =>
|
|
courses.map(course => ({
|
|
id: course.id,
|
|
name: course.courseName
|
|
}))
|
|
, [courses]);
|
|
|
|
// 외부 클릭 시 드롭다운 닫기
|
|
useEffect(() => {
|
|
const handleClickOutside = (event: MouseEvent) => {
|
|
if (
|
|
dropdownRef.current &&
|
|
!dropdownRef.current.contains(event.target as Node)
|
|
) {
|
|
setIsDropdownOpen(false);
|
|
}
|
|
};
|
|
|
|
if (isDropdownOpen) {
|
|
document.addEventListener("mousedown", handleClickOutside);
|
|
}
|
|
|
|
return () => {
|
|
document.removeEventListener("mousedown", handleClickOutside);
|
|
};
|
|
}, [isDropdownOpen]);
|
|
|
|
const handleBackClick = () => {
|
|
setIsRegistrationMode(false);
|
|
// 폼 초기화
|
|
setSelectedCourse("");
|
|
setLessonName("");
|
|
setLearningGoal("");
|
|
setCourseVideoCount(0);
|
|
setCourseVideoFiles([]);
|
|
setCourseVideoFileObjects([]);
|
|
setCourseVideoFileKeys([]);
|
|
setVrContentCount(0);
|
|
setVrContentFiles([]);
|
|
setVrContentFileObjects([]);
|
|
setVrContentFileKeys([]);
|
|
setQuestionFileCount(0);
|
|
setQuestionFileObject(null);
|
|
setQuestionFileKey(null);
|
|
setCsvData([]);
|
|
setCsvHeaders([]);
|
|
setCsvRows([]);
|
|
setErrors({});
|
|
};
|
|
|
|
const handleRegisterClick = () => {
|
|
setIsRegistrationMode(true);
|
|
};
|
|
|
|
// 파일 업로드 함수
|
|
const handleVideoFileUpload = async (validFiles: File[]) => {
|
|
try {
|
|
let fileKeys: string[] = [];
|
|
|
|
// 파일이 1개인 경우 uploadFile 사용
|
|
if (validFiles.length === 1) {
|
|
const uploadResponse = await apiService.uploadFile(validFiles[0]);
|
|
|
|
// 응답에서 fileKey 추출
|
|
const fileKey = uploadResponse.data?.fileKey
|
|
|| uploadResponse.data?.key
|
|
|| uploadResponse.data?.id
|
|
|| uploadResponse.data?.fileId;
|
|
|
|
if (fileKey) {
|
|
fileKeys = [fileKey];
|
|
} else {
|
|
throw new Error('파일 업로드는 완료되었지만 fileKey를 받지 못했습니다.');
|
|
}
|
|
} else {
|
|
// 파일이 2개 이상인 경우 uploadFiles 사용
|
|
const uploadResponse = await apiService.uploadFiles(validFiles);
|
|
|
|
// 응답에서 fileKey 배열 추출
|
|
if (uploadResponse.data?.results && Array.isArray(uploadResponse.data.results)) {
|
|
uploadResponse.data.results.forEach((result: any) => {
|
|
if (result.ok && result.fileKey) {
|
|
fileKeys.push(result.fileKey);
|
|
} else if (result.fileKey) {
|
|
fileKeys.push(result.fileKey);
|
|
}
|
|
});
|
|
} else if (Array.isArray(uploadResponse.data)) {
|
|
// 응답이 배열인 경우
|
|
fileKeys = uploadResponse.data.map((item: any) =>
|
|
item.fileKey || item.key || item.id || item.fileId
|
|
).filter(Boolean);
|
|
} else if (uploadResponse.data?.fileKeys && Array.isArray(uploadResponse.data.fileKeys)) {
|
|
fileKeys = uploadResponse.data.fileKeys;
|
|
}
|
|
}
|
|
|
|
if (fileKeys.length > 0) {
|
|
// 이전 파일 삭제하고 새 파일로 교체
|
|
setCourseVideoFiles(validFiles.map(f => f.name));
|
|
setCourseVideoFileObjects(validFiles);
|
|
setCourseVideoFileKeys(fileKeys);
|
|
setCourseVideoCount(fileKeys.length);
|
|
} else {
|
|
throw new Error('파일 업로드는 완료되었지만 fileKey를 받지 못했습니다.');
|
|
}
|
|
} catch (error) {
|
|
console.error('강좌 영상 업로드 실패:', error);
|
|
alert('파일 업로드에 실패했습니다. 다시 시도해주세요.');
|
|
}
|
|
};
|
|
|
|
const handleVrFileUpload = async (validFiles: File[]) => {
|
|
try {
|
|
let fileKeys: string[] = [];
|
|
|
|
// 파일이 1개인 경우 uploadFile 사용
|
|
if (validFiles.length === 1) {
|
|
const uploadResponse = await apiService.uploadFile(validFiles[0]);
|
|
|
|
// 응답에서 fileKey 추출
|
|
const fileKey = uploadResponse.data?.fileKey
|
|
|| uploadResponse.data?.key
|
|
|| uploadResponse.data?.id
|
|
|| uploadResponse.data?.fileId;
|
|
|
|
if (fileKey) {
|
|
fileKeys = [fileKey];
|
|
} else {
|
|
throw new Error('파일 업로드는 완료되었지만 fileKey를 받지 못했습니다.');
|
|
}
|
|
} else {
|
|
// 파일이 2개 이상인 경우 uploadFiles 사용
|
|
const uploadResponse = await apiService.uploadFiles(validFiles);
|
|
|
|
// 응답에서 fileKey 배열 추출
|
|
if (uploadResponse.data?.results && Array.isArray(uploadResponse.data.results)) {
|
|
uploadResponse.data.results.forEach((result: any) => {
|
|
if (result.ok && result.fileKey) {
|
|
fileKeys.push(result.fileKey);
|
|
} else if (result.fileKey) {
|
|
fileKeys.push(result.fileKey);
|
|
}
|
|
});
|
|
} else if (Array.isArray(uploadResponse.data)) {
|
|
// 응답이 배열인 경우
|
|
fileKeys = uploadResponse.data.map((item: any) =>
|
|
item.fileKey || item.key || item.id || item.fileId
|
|
).filter(Boolean);
|
|
} else if (uploadResponse.data?.fileKeys && Array.isArray(uploadResponse.data.fileKeys)) {
|
|
fileKeys = uploadResponse.data.fileKeys;
|
|
}
|
|
}
|
|
|
|
if (fileKeys.length > 0) {
|
|
// 이전 파일 삭제하고 새 파일로 교체
|
|
setVrContentFiles(validFiles.map(f => f.name));
|
|
setVrContentFileObjects(validFiles);
|
|
setVrContentFileKeys(fileKeys);
|
|
setVrContentCount(fileKeys.length);
|
|
} else {
|
|
throw new Error('파일 업로드는 완료되었지만 fileKey를 받지 못했습니다.');
|
|
}
|
|
} catch (error) {
|
|
console.error('VR 콘텐츠 업로드 실패:', error);
|
|
alert('파일 업로드에 실패했습니다. 다시 시도해주세요.');
|
|
}
|
|
};
|
|
|
|
const handleCsvFileUpload = async (file: File) => {
|
|
try {
|
|
// CSV 파일 파싱
|
|
const reader = new FileReader();
|
|
reader.onload = (event) => {
|
|
const text = event.target?.result as string;
|
|
if (!text) return;
|
|
|
|
try {
|
|
// CSV 파싱 함수
|
|
const parseCsv = (csvText: string): string[][] => {
|
|
const lines: string[][] = [];
|
|
let currentLine: string[] = [];
|
|
let currentField = '';
|
|
let inQuotes = false;
|
|
|
|
for (let i = 0; i < csvText.length; i++) {
|
|
const char = csvText[i];
|
|
const nextChar = csvText[i + 1];
|
|
|
|
if (char === '"') {
|
|
if (inQuotes && nextChar === '"') {
|
|
currentField += '"';
|
|
i++;
|
|
} else {
|
|
inQuotes = !inQuotes;
|
|
}
|
|
} else if (char === ',' && !inQuotes) {
|
|
currentLine.push(currentField.trim());
|
|
currentField = '';
|
|
} else if ((char === '\n' || char === '\r') && !inQuotes) {
|
|
if (char === '\r' && nextChar === '\n') {
|
|
i++;
|
|
}
|
|
if (currentField || currentLine.length > 0) {
|
|
currentLine.push(currentField.trim());
|
|
lines.push(currentLine);
|
|
currentLine = [];
|
|
currentField = '';
|
|
}
|
|
} else {
|
|
currentField += char;
|
|
}
|
|
}
|
|
|
|
if (currentField || currentLine.length > 0) {
|
|
currentLine.push(currentField.trim());
|
|
lines.push(currentLine);
|
|
}
|
|
|
|
return lines;
|
|
};
|
|
|
|
const parsed = parseCsv(text);
|
|
|
|
if (parsed.length === 0) {
|
|
alert('CSV 파일이 비어있습니다.');
|
|
return;
|
|
}
|
|
|
|
// 첫 번째 줄을 헤더로 사용
|
|
const headers = parsed[0];
|
|
const rows = parsed.slice(1);
|
|
|
|
setCsvHeaders(headers);
|
|
setCsvRows(rows);
|
|
setCsvData(parsed);
|
|
} catch (parseError) {
|
|
console.error('CSV 파싱 오류:', parseError);
|
|
alert('CSV 파일을 읽는 중 오류가 발생했습니다.');
|
|
}
|
|
};
|
|
|
|
reader.onerror = () => {
|
|
alert('파일을 읽는 중 오류가 발생했습니다.');
|
|
};
|
|
|
|
reader.readAsText(file, 'UTF-8');
|
|
|
|
// 단일 파일 업로드
|
|
const uploadResponse = await apiService.uploadFile(file);
|
|
|
|
// 응답에서 fileKey 추출
|
|
const fileKey = uploadResponse.data?.fileKey
|
|
|| uploadResponse.data?.key
|
|
|| uploadResponse.data?.id
|
|
|| uploadResponse.data?.fileId
|
|
|| uploadResponse.data?.imageKey
|
|
|| (uploadResponse.data?.data && (uploadResponse.data.data.key || uploadResponse.data.data.fileKey))
|
|
|| null;
|
|
|
|
if (fileKey) {
|
|
// 이전 파일 삭제하고 새 파일로 교체
|
|
setQuestionFileObject(file);
|
|
setQuestionFileKey(fileKey);
|
|
setQuestionFileCount(1);
|
|
} else {
|
|
throw new Error('파일 업로드는 완료되었지만 fileKey를 받지 못했습니다.');
|
|
}
|
|
} catch (error) {
|
|
console.error('학습 평가 문제 업로드 실패:', error);
|
|
alert('파일 업로드에 실패했습니다. 다시 시도해주세요.');
|
|
}
|
|
};
|
|
|
|
// 파일 교체 확인 모달 핸들러
|
|
const handleFileReplaceConfirm = async () => {
|
|
if (!pendingFiles.length || !pendingFileType) return;
|
|
|
|
setIsFileReplaceModalOpen(false);
|
|
|
|
if (pendingFileType === 'video') {
|
|
await handleVideoFileUpload(pendingFiles);
|
|
} else if (pendingFileType === 'vr') {
|
|
await handleVrFileUpload(pendingFiles);
|
|
} else if (pendingFileType === 'csv' && pendingFiles.length > 0) {
|
|
await handleCsvFileUpload(pendingFiles[0]);
|
|
}
|
|
|
|
setPendingFiles([]);
|
|
setPendingFileType(null);
|
|
};
|
|
|
|
const handleFileReplaceCancel = () => {
|
|
setIsFileReplaceModalOpen(false);
|
|
setPendingFiles([]);
|
|
setPendingFileType(null);
|
|
};
|
|
|
|
const handleSaveClick = async () => {
|
|
// 유효성 검사
|
|
const newErrors: {
|
|
selectedCourse?: string;
|
|
lessonName?: string;
|
|
learningGoal?: string;
|
|
} = {};
|
|
|
|
if (!selectedCourse) {
|
|
newErrors.selectedCourse = "교육과정을 선택해 주세요.";
|
|
}
|
|
if (!lessonName.trim()) {
|
|
newErrors.lessonName = "강좌명을 입력해 주세요.";
|
|
}
|
|
if (!learningGoal.trim()) {
|
|
newErrors.learningGoal = "내용을 입력해 주세요.";
|
|
}
|
|
|
|
// 에러가 있으면 표시하고 중단
|
|
if (Object.keys(newErrors).length > 0) {
|
|
setErrors(newErrors);
|
|
return;
|
|
}
|
|
|
|
// 에러 초기화
|
|
setErrors({});
|
|
|
|
try {
|
|
// 이미 업로드된 fileKey 배열 사용
|
|
const videoFileKeys = courseVideoFileKeys;
|
|
const vrFileKeys = vrContentFileKeys;
|
|
const csvFileKey = questionFileKey;
|
|
|
|
// 강좌 영상 fileKey (단일 파일은 문자열, 다중 파일은 배열)
|
|
let videoUrl: string | string[] | undefined;
|
|
if (videoFileKeys.length === 1) {
|
|
videoUrl = videoFileKeys[0]; // 단일 파일은 문자열로
|
|
} else if (videoFileKeys.length > 1) {
|
|
videoUrl = videoFileKeys; // 다중 파일은 배열로
|
|
}
|
|
|
|
// VR 콘텐츠 fileKey (단일 파일은 문자열, 다중 파일은 배열)
|
|
let webglUrl: string | string[] | undefined;
|
|
if (vrFileKeys.length === 1) {
|
|
webglUrl = vrFileKeys[0]; // 단일 파일은 문자열로
|
|
} else if (vrFileKeys.length > 1) {
|
|
webglUrl = vrFileKeys; // 다중 파일은 배열로
|
|
}
|
|
|
|
// 학습 평가 문제 fileKey
|
|
let csvKey: string | undefined;
|
|
if (csvFileKey) {
|
|
csvKey = csvFileKey;
|
|
}
|
|
|
|
// API 요청 body 구성
|
|
const requestBody: {
|
|
subjectId: number;
|
|
title: string;
|
|
objective: string;
|
|
videoUrl?: string | string[];
|
|
webglUrl?: string | string[];
|
|
csvKey?: string;
|
|
} = {
|
|
subjectId: Number(selectedCourse),
|
|
title: lessonName.trim(),
|
|
objective: learningGoal.trim(),
|
|
};
|
|
|
|
// 선택적 필드 추가
|
|
if (videoUrl) {
|
|
requestBody.videoUrl = videoUrl;
|
|
}
|
|
if (webglUrl) {
|
|
requestBody.webglUrl = webglUrl;
|
|
}
|
|
if (csvKey) {
|
|
requestBody.csvKey = csvKey;
|
|
}
|
|
|
|
// 강좌 등록 API 호출
|
|
const response = await apiService.createLecture(requestBody);
|
|
|
|
// 응답에서 id 추출 및 저장
|
|
const lectureId = response.data?.id;
|
|
if (!lectureId) {
|
|
throw new Error('강좌 등록 응답에서 ID를 받지 못했습니다.');
|
|
}
|
|
|
|
// 첨부파일 정보 문자열 생성
|
|
const attachmentParts: string[] = [];
|
|
if (courseVideoCount > 0) {
|
|
attachmentParts.push(`강좌영상 ${courseVideoCount}개`);
|
|
}
|
|
if (vrContentCount > 0) {
|
|
attachmentParts.push(`VR콘텐츠 ${vrContentCount}개`);
|
|
}
|
|
if (questionFileCount > 0) {
|
|
attachmentParts.push(`평가문제 ${questionFileCount}개`);
|
|
}
|
|
const attachments = attachmentParts.length > 0
|
|
? attachmentParts.join(', ')
|
|
: '없음';
|
|
|
|
// 교육과정명 가져오기
|
|
const courseName = courseOptions.find(c => c.id === selectedCourse)?.name || '';
|
|
|
|
// 새 강좌 생성 (API 응답의 id 사용)
|
|
const newLesson: Lesson = {
|
|
id: String(lectureId),
|
|
courseName,
|
|
lessonName,
|
|
attachments,
|
|
questionCount: questionFileCount,
|
|
createdBy: currentUser,
|
|
createdAt: new Date().toISOString().split('T')[0],
|
|
};
|
|
|
|
// 강좌 목록에 추가
|
|
setLessons(prev => [...prev, newLesson]);
|
|
|
|
// 등록 모드 종료 및 폼 초기화
|
|
setIsRegistrationMode(false);
|
|
setSelectedCourse("");
|
|
setLessonName("");
|
|
setLearningGoal("");
|
|
setCourseVideoCount(0);
|
|
setCourseVideoFiles([]);
|
|
setCourseVideoFileObjects([]);
|
|
setCourseVideoFileKeys([]);
|
|
setVrContentCount(0);
|
|
setVrContentFiles([]);
|
|
setVrContentFileObjects([]);
|
|
setVrContentFileKeys([]);
|
|
setQuestionFileCount(0);
|
|
setQuestionFileObject(null);
|
|
setQuestionFileKey(null);
|
|
setCsvData([]);
|
|
setCsvHeaders([]);
|
|
setCsvRows([]);
|
|
|
|
// 토스트 팝업 표시
|
|
setToastMessage('강좌가 등록되었습니다.');
|
|
setShowToast(true);
|
|
} catch (error) {
|
|
console.error('강좌 등록 실패:', error);
|
|
const errorMessage = error instanceof Error ? error.message : '강좌 등록 중 오류가 발생했습니다.';
|
|
alert(errorMessage);
|
|
}
|
|
};
|
|
|
|
// 쿼리 파라미터에서 updated 확인하여 토스트 표시
|
|
useEffect(() => {
|
|
const updated = searchParams.get('updated');
|
|
if (updated === 'true') {
|
|
setToastMessage('강좌가 수정되었습니다.');
|
|
setShowToast(true);
|
|
// URL에서 쿼리 파라미터 제거
|
|
const newUrl = window.location.pathname;
|
|
router.replace(newUrl);
|
|
}
|
|
}, [searchParams, router]);
|
|
|
|
// 토스트 자동 닫기
|
|
useEffect(() => {
|
|
if (showToast) {
|
|
const timer = setTimeout(() => {
|
|
setShowToast(false);
|
|
}, 3000); // 3초 후 자동 닫기
|
|
|
|
return () => clearTimeout(timer);
|
|
}
|
|
}, [showToast]);
|
|
|
|
return (
|
|
<div className="min-h-screen flex flex-col bg-white">
|
|
{/* 메인 레이아웃 */}
|
|
<div className="flex flex-1 min-h-0 justify-center">
|
|
<div className="w-[1440px] flex min-h-0">
|
|
{/* 사이드바 */}
|
|
<div className="flex">
|
|
<AdminSidebar />
|
|
</div>
|
|
{/* 메인 콘텐츠 */}
|
|
<main className="w-[1120px] bg-white">
|
|
<div className="h-full flex flex-col px-8">
|
|
{isRegistrationMode ? (
|
|
/* 등록 모드 */
|
|
<div className="flex flex-col h-full">
|
|
{/* 헤더 */}
|
|
<div className="h-[100px] flex items-center">
|
|
<div className="flex items-center gap-[12px]">
|
|
<button
|
|
type="button"
|
|
onClick={handleBackClick}
|
|
className="flex items-center justify-center size-[32px] cursor-pointer hover:opacity-80"
|
|
aria-label="뒤로가기"
|
|
>
|
|
<BackArrowSvg width={32} height={32} />
|
|
</button>
|
|
<h1 className="text-[24px] font-bold leading-[1.5] text-[#1b2027]">
|
|
강좌 등록
|
|
</h1>
|
|
</div>
|
|
</div>
|
|
|
|
{/* 폼 콘텐츠 */}
|
|
<div className="flex-1 overflow-y-auto pb-[80px] pt-[32px]">
|
|
<div className="flex flex-col gap-[40px]">
|
|
{/* 강좌 정보 */}
|
|
<div className="flex flex-col gap-[8px]">
|
|
<h2 className="text-[18px] font-bold leading-[1.5] text-[#1b2027]">
|
|
강좌 정보
|
|
</h2>
|
|
<div className="flex flex-col gap-[24px]">
|
|
{/* 교육 과정 */}
|
|
<div className="flex flex-col gap-[8px] max-w-[480px]">
|
|
<label className="text-[15px] font-semibold leading-[1.5] text-[#6c7682]">
|
|
교육 과정
|
|
</label>
|
|
<div className="relative" ref={dropdownRef}>
|
|
<button
|
|
type="button"
|
|
onClick={() => setIsDropdownOpen(!isDropdownOpen)}
|
|
className={`w-full h-[40px] px-[12px] py-[8px] border rounded-[8px] bg-white flex items-center justify-between focus:outline-none focus:shadow-[inset_0_0_0_1px_#333c47] cursor-pointer ${
|
|
errors.selectedCourse ? 'border-[#e63946]' : 'border-[#dee1e6]'
|
|
}`}
|
|
>
|
|
<span className={`text-[16px] font-normal leading-[1.5] flex-1 text-left ${
|
|
selectedCourse ? 'text-[#1b2027]' : 'text-[#6c7682]'
|
|
}`}>
|
|
{selectedCourse
|
|
? courseOptions.find(c => c.id === selectedCourse)?.name
|
|
: '교육과정을 선택해 주세요.'}
|
|
</span>
|
|
<DropdownIcon stroke="#8C95A1" className="shrink-0" />
|
|
</button>
|
|
{isDropdownOpen && (
|
|
<div className="absolute top-full left-0 right-0 mt-1 bg-white border border-[#dee1e6] rounded-[8px] shadow-lg z-20 max-h-[200px] overflow-y-auto dropdown-scroll">
|
|
{courseOptions.map((course, index) => (
|
|
<button
|
|
key={course.id}
|
|
type="button"
|
|
onClick={() => {
|
|
setSelectedCourse(course.id);
|
|
setIsDropdownOpen(false);
|
|
// 에러 초기화
|
|
if (errors.selectedCourse) {
|
|
setErrors(prev => ({ ...prev, selectedCourse: undefined }));
|
|
}
|
|
}}
|
|
className={`w-full px-3 py-2 text-left text-[16px] font-normal leading-[1.5] hover:bg-[#f1f3f5] transition-colors cursor-pointer ${
|
|
selectedCourse === course.id
|
|
? "bg-[#ecf0ff] text-[#1f2b91] font-semibold"
|
|
: "text-[#1b2027]"
|
|
} ${
|
|
index === 0 ? "rounded-t-[8px]" : ""
|
|
} ${
|
|
index === courseOptions.length - 1 ? "rounded-b-[8px]" : ""
|
|
}`}
|
|
>
|
|
{course.name}
|
|
</button>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
{errors.selectedCourse && (
|
|
<p className="text-[14px] font-normal leading-[1.5] text-[#e63946]">
|
|
{errors.selectedCourse}
|
|
</p>
|
|
)}
|
|
</div>
|
|
|
|
{/* 강좌명 */}
|
|
<div className="flex flex-col gap-[8px]">
|
|
<label className="text-[15px] font-semibold leading-[1.5] text-[#6c7682]">
|
|
강좌명
|
|
</label>
|
|
<input
|
|
type="text"
|
|
value={lessonName}
|
|
onChange={(e) => {
|
|
setLessonName(e.target.value);
|
|
// 에러 초기화
|
|
if (errors.lessonName) {
|
|
setErrors(prev => ({ ...prev, lessonName: undefined }));
|
|
}
|
|
}}
|
|
placeholder="강좌명을 입력해 주세요."
|
|
className={`h-[40px] px-[12px] py-[8px] border rounded-[8px] bg-white text-[16px] font-normal leading-[1.5] text-[#1b2027] placeholder:text-[#b1b8c0] focus:outline-none focus:shadow-[inset_0_0_0_1px_#333c47] ${
|
|
errors.lessonName ? 'border-[#e63946]' : 'border-[#dee1e6]'
|
|
}`}
|
|
/>
|
|
{errors.lessonName && (
|
|
<p className="text-[14px] font-normal leading-[1.5] text-[#e63946]">
|
|
{errors.lessonName}
|
|
</p>
|
|
)}
|
|
</div>
|
|
|
|
{/* 학습 목표 */}
|
|
<div className="flex flex-col gap-[8px]">
|
|
<label className="text-[15px] font-semibold leading-[1.5] text-[#6c7682]">
|
|
학습 목표
|
|
</label>
|
|
<div className="relative">
|
|
<textarea
|
|
value={learningGoal}
|
|
onChange={(e) => {
|
|
if (e.target.value.length <= 1000) {
|
|
setLearningGoal(e.target.value);
|
|
// 에러 초기화
|
|
if (errors.learningGoal) {
|
|
setErrors(prev => ({ ...prev, learningGoal: undefined }));
|
|
}
|
|
}
|
|
}}
|
|
placeholder="내용을 입력해 주세요. (최대 1,000자)"
|
|
className={`w-full h-[160px] px-[12px] py-[8px] border rounded-[8px] bg-white text-[16px] font-normal leading-[1.5] text-[#1b2027] placeholder:text-[#b1b8c0] focus:outline-none focus:shadow-[inset_0_0_0_1px_#333c47] resize-none ${
|
|
errors.learningGoal ? 'border-[#e63946]' : 'border-[#dee1e6]'
|
|
}`}
|
|
/>
|
|
<div className="absolute bottom-[8px] right-[12px]">
|
|
<p className="text-[13px] font-normal leading-[1.4] text-[#6c7682] text-right">
|
|
{learningGoal.length}/1000
|
|
</p>
|
|
</div>
|
|
</div>
|
|
{errors.learningGoal && (
|
|
<p className="text-[14px] font-normal leading-[1.5] text-[#e63946]">
|
|
{errors.learningGoal}
|
|
</p>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{/* 파일 첨부 */}
|
|
<div className="flex flex-col gap-[8px]">
|
|
<h2 className="text-[18px] font-bold leading-[1.5] text-[#1b2027]">
|
|
파일 첨부
|
|
</h2>
|
|
<div className="flex flex-col gap-[24px]">
|
|
{/* 강좌 영상 */}
|
|
<div className="flex flex-col gap-[8px]">
|
|
<div className="flex items-center justify-between h-[32px]">
|
|
<div className="flex items-center gap-[8px]">
|
|
<label className="text-[15px] font-semibold leading-[1.5] text-[#6c7682]">
|
|
강좌 영상 ({courseVideoCount}/10)
|
|
</label>
|
|
<span className="text-[13px] font-normal leading-[1.4] text-[#8c95a1]">
|
|
30MB 미만 파일
|
|
</span>
|
|
</div>
|
|
<label className="h-[32px] w-[62px] px-[4px] py-[3px] border border-[#8c95a1] rounded-[6px] bg-white text-[13px] font-medium leading-[1.4] text-[#4c5561] whitespace-nowrap hover:bg-gray-50 transition-colors cursor-pointer flex items-center justify-center">
|
|
<span>첨부</span>
|
|
<input
|
|
type="file"
|
|
multiple
|
|
accept=".mp4,.avi,.mov,.wmv,.flv,.webm,.mkv,video/mp4,video/avi,video/quicktime,video/x-ms-wmv,video/x-flv,video/webm,video/x-matroska"
|
|
className="hidden"
|
|
onChange={async (e) => {
|
|
const files = e.target.files;
|
|
if (!files) return;
|
|
|
|
const MAX_SIZE = 30 * 1024 * 1024; // 30MB
|
|
const MAX_COUNT = 10; // 최대 10개
|
|
const validFiles: File[] = [];
|
|
const oversizedFiles: string[] = [];
|
|
const invalidTypeFiles: string[] = [];
|
|
|
|
// 영상 파일 확장자 확인
|
|
const videoExtensions = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm', '.mkv'];
|
|
|
|
Array.from(files).forEach((file) => {
|
|
const fileExtension = file.name.toLowerCase().substring(file.name.lastIndexOf('.'));
|
|
if (!videoExtensions.includes(fileExtension)) {
|
|
invalidTypeFiles.push(file.name);
|
|
return;
|
|
}
|
|
// 각 파일이 30MB 이하인지 검사
|
|
if (file.size <= MAX_SIZE) {
|
|
validFiles.push(file);
|
|
} else {
|
|
oversizedFiles.push(file.name);
|
|
}
|
|
});
|
|
|
|
// 파일 타입 오류
|
|
if (invalidTypeFiles.length > 0) {
|
|
alert(`다음 파일은 영상 파일 형식만 가능합니다 (MP4, AVI, MOV, WMV, FLV, WEBM, MKV):\n${invalidTypeFiles.join('\n')}`);
|
|
}
|
|
|
|
// 30MB 초과 파일이 있으면 알림
|
|
if (oversizedFiles.length > 0) {
|
|
alert(`다음 파일은 30MB 이하여야 합니다:\n${oversizedFiles.join('\n')}`);
|
|
}
|
|
|
|
// 파일 개수 제한 확인
|
|
const totalCount = courseVideoCount + validFiles.length;
|
|
if (totalCount > MAX_COUNT) {
|
|
const availableCount = MAX_COUNT - courseVideoCount;
|
|
alert(`강좌 영상은 최대 ${MAX_COUNT}개까지 첨부할 수 있습니다. (현재 ${courseVideoCount}개, 추가 가능 ${availableCount > 0 ? availableCount : 0}개)`);
|
|
e.target.value = '';
|
|
return;
|
|
}
|
|
|
|
// 30MB 초과 파일이나 잘못된 타입 파일만 있는 경우 중단
|
|
if (validFiles.length === 0 && (oversizedFiles.length > 0 || invalidTypeFiles.length > 0)) {
|
|
e.target.value = '';
|
|
return;
|
|
}
|
|
|
|
if (validFiles.length > 0) {
|
|
// 기존 파일이 있으면 확인 모달 표시
|
|
if (courseVideoFiles.length > 0 || courseVideoFileKeys.length > 0) {
|
|
setPendingFiles(validFiles);
|
|
setPendingFileType('video');
|
|
setIsFileReplaceModalOpen(true);
|
|
e.target.value = '';
|
|
return;
|
|
}
|
|
|
|
// 기존 파일이 없으면 바로 업로드
|
|
handleVideoFileUpload(validFiles);
|
|
}
|
|
// input 초기화 (같은 파일 다시 선택 가능하도록)
|
|
e.target.value = '';
|
|
}}
|
|
/>
|
|
</label>
|
|
</div>
|
|
<div className="border border-[#dee1e6] rounded-[8px] bg-gray-50">
|
|
{courseVideoFiles.length === 0 ? (
|
|
<div className="h-[64px] flex items-center justify-center">
|
|
<p className="text-[14px] font-normal leading-[1.5] text-[#8c95a1] text-center">
|
|
강좌 주제별 영상 파일을 첨부해주세요.
|
|
</p>
|
|
</div>
|
|
) : (
|
|
<div className="flex flex-col py-[12px]">
|
|
{courseVideoFiles.map((fileName, index) => (
|
|
<div
|
|
key={index}
|
|
className="h-[40px] px-[20px] py-[12px] flex items-center gap-[12px]"
|
|
>
|
|
<p className="flex-1 text-[15px] font-normal leading-[1.5] text-[#333c47]">
|
|
{fileName}
|
|
</p>
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
setCourseVideoFiles(prev => prev.filter((_, i) => i !== index));
|
|
setCourseVideoFileObjects(prev => prev.filter((_, i) => i !== index));
|
|
setCourseVideoFileKeys(prev => prev.filter((_, i) => i !== index));
|
|
setCourseVideoCount(prev => prev - 1);
|
|
}}
|
|
className="size-[16px] flex items-center justify-center cursor-pointer hover:opacity-70 transition-opacity shrink-0"
|
|
aria-label="파일 삭제"
|
|
>
|
|
<CloseXOSvg />
|
|
</button>
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
{/* VR 콘텐츠 */}
|
|
<div className="flex flex-col gap-[8px]">
|
|
<div className="flex items-center justify-between h-[32px]">
|
|
<div className="flex items-center gap-[8px]">
|
|
<label className="text-[15px] font-semibold leading-[1.5] text-[#6c7682]">
|
|
VR 콘텐츠 ({vrContentCount}/10)
|
|
</label>
|
|
<span className="text-[13px] font-normal leading-[1.4] text-[#8c95a1]">
|
|
30MB 미만 파일
|
|
</span>
|
|
</div>
|
|
<label className="h-[32px] w-[62px] px-[4px] py-[3px] border border-[#8c95a1] rounded-[6px] bg-white text-[13px] font-medium leading-[1.4] text-[#4c5561] whitespace-nowrap hover:bg-gray-50 transition-colors cursor-pointer flex items-center justify-center">
|
|
<span>첨부</span>
|
|
<input
|
|
type="file"
|
|
multiple
|
|
accept=".zip,application/zip"
|
|
className="hidden"
|
|
onChange={async (e) => {
|
|
const files = e.target.files;
|
|
if (!files) return;
|
|
|
|
const MAX_SIZE = 30 * 1024 * 1024; // 30MB
|
|
const MAX_COUNT = 10; // 최대 10개
|
|
const validFiles: File[] = [];
|
|
const oversizedFiles: string[] = [];
|
|
const invalidTypeFiles: string[] = [];
|
|
|
|
Array.from(files).forEach((file) => {
|
|
// ZIP 파일인지 확인
|
|
const fileExtension = file.name.toLowerCase().substring(file.name.lastIndexOf('.'));
|
|
if (fileExtension !== '.zip') {
|
|
invalidTypeFiles.push(file.name);
|
|
return;
|
|
}
|
|
// 각 파일이 30MB 이하인지 검사
|
|
if (file.size <= MAX_SIZE) {
|
|
validFiles.push(file);
|
|
} else {
|
|
oversizedFiles.push(file.name);
|
|
}
|
|
});
|
|
|
|
// 파일 타입 오류
|
|
if (invalidTypeFiles.length > 0) {
|
|
alert(`다음 파일은 ZIP 형식만 가능합니다:\n${invalidTypeFiles.join('\n')}`);
|
|
}
|
|
|
|
// 30MB 초과 파일이 있으면 알림
|
|
if (oversizedFiles.length > 0) {
|
|
alert(`다음 파일은 30MB 이하여야 합니다:\n${oversizedFiles.join('\n')}`);
|
|
}
|
|
|
|
// 파일 개수 제한 확인
|
|
const totalCount = vrContentCount + validFiles.length;
|
|
if (totalCount > MAX_COUNT) {
|
|
const availableCount = MAX_COUNT - vrContentCount;
|
|
alert(`VR 콘텐츠는 최대 ${MAX_COUNT}개까지 첨부할 수 있습니다. (현재 ${vrContentCount}개, 추가 가능 ${availableCount > 0 ? availableCount : 0}개)`);
|
|
e.target.value = '';
|
|
return;
|
|
}
|
|
|
|
// 30MB 초과 파일이나 잘못된 타입 파일만 있는 경우 중단
|
|
if (validFiles.length === 0 && (oversizedFiles.length > 0 || invalidTypeFiles.length > 0)) {
|
|
e.target.value = '';
|
|
return;
|
|
}
|
|
|
|
if (validFiles.length > 0) {
|
|
// 기존 파일이 있으면 확인 모달 표시
|
|
if (vrContentFiles.length > 0 || vrContentFileKeys.length > 0) {
|
|
setPendingFiles(validFiles);
|
|
setPendingFileType('vr');
|
|
setIsFileReplaceModalOpen(true);
|
|
e.target.value = '';
|
|
return;
|
|
}
|
|
|
|
// 기존 파일이 없으면 바로 업로드
|
|
handleVrFileUpload(validFiles);
|
|
}
|
|
// input 초기화 (같은 파일 다시 선택 가능하도록)
|
|
e.target.value = '';
|
|
}}
|
|
/>
|
|
</label>
|
|
</div>
|
|
<div className="border border-[#dee1e6] rounded-[8px] bg-gray-50">
|
|
{vrContentFiles.length === 0 ? (
|
|
<div className="h-[64px] flex items-center justify-center">
|
|
<p className="text-[14px] font-normal leading-[1.5] text-[#8c95a1] text-center">
|
|
VR 학습 체험용 콘텐츠 파일을 첨부해주세요.
|
|
</p>
|
|
</div>
|
|
) : (
|
|
<div className="flex flex-col py-[12px]">
|
|
{vrContentFiles.map((fileName, index) => (
|
|
<div
|
|
key={index}
|
|
className="h-[40px] px-[20px] py-[12px] flex items-center gap-[12px]"
|
|
>
|
|
<p className="flex-1 text-[15px] font-normal leading-[1.5] text-[#333c47]">
|
|
{fileName}
|
|
</p>
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
setVrContentFiles(prev => prev.filter((_, i) => i !== index));
|
|
setVrContentFileObjects(prev => prev.filter((_, i) => i !== index));
|
|
setVrContentFileKeys(prev => prev.filter((_, i) => i !== index));
|
|
setVrContentCount(prev => prev - 1);
|
|
}}
|
|
className="size-[16px] flex items-center justify-center cursor-pointer hover:opacity-70 transition-opacity shrink-0"
|
|
aria-label="파일 삭제"
|
|
>
|
|
<CloseXOSvg />
|
|
</button>
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
{/* 학습 평가 문제 */}
|
|
<div className="flex flex-col gap-[8px]">
|
|
<div className="flex items-center justify-between h-[32px]">
|
|
<div className="flex items-center gap-[8px]">
|
|
<label className="text-[15px] font-semibold leading-[1.5] text-[#6c7682]">
|
|
학습 평가 문제
|
|
</label>
|
|
<span className="text-[13px] font-normal leading-[1.4] text-[#8c95a1]">
|
|
CSV 파일 형식만 첨부 가능
|
|
</span>
|
|
</div>
|
|
<div className="flex items-center gap-[8px]">
|
|
<button
|
|
type="button"
|
|
className="h-[32px] px-[16px] py-[3px] border border-[#b1b8c0] rounded-[6px] bg-white text-[13px] font-medium leading-[1.4] text-[#b1b8c0] whitespace-nowrap hover:bg-gray-50 transition-colors cursor-pointer"
|
|
>
|
|
다운로드
|
|
</button>
|
|
<label className="h-[32px] w-[62px] px-[4px] py-[3px] border border-[#8c95a1] rounded-[6px] bg-white text-[13px] font-medium leading-[1.4] text-[#4c5561] whitespace-nowrap hover:bg-gray-50 transition-colors cursor-pointer flex items-center justify-center">
|
|
<span>첨부</span>
|
|
<input
|
|
type="file"
|
|
accept=".csv,text/csv,application/vnd.ms-excel"
|
|
className="hidden"
|
|
onChange={async (e) => {
|
|
const files = e.target.files;
|
|
if (!files || files.length === 0) return;
|
|
|
|
const file = files[0];
|
|
|
|
// CSV 파일만 허용
|
|
if (!file.name.toLowerCase().endsWith('.csv')) {
|
|
alert('CSV 파일 형식만 첨부할 수 있습니다.');
|
|
e.target.value = '';
|
|
return;
|
|
}
|
|
|
|
try {
|
|
// CSV 파일 파싱
|
|
const reader = new FileReader();
|
|
reader.onload = (event) => {
|
|
const text = event.target?.result as string;
|
|
if (!text) return;
|
|
|
|
try {
|
|
// CSV 파싱 함수
|
|
const parseCsv = (csvText: string): string[][] => {
|
|
const lines: string[][] = [];
|
|
let currentLine: string[] = [];
|
|
let currentField = '';
|
|
let inQuotes = false;
|
|
|
|
for (let i = 0; i < csvText.length; i++) {
|
|
const char = csvText[i];
|
|
const nextChar = csvText[i + 1];
|
|
|
|
if (char === '"') {
|
|
if (inQuotes && nextChar === '"') {
|
|
currentField += '"';
|
|
i++;
|
|
} else {
|
|
inQuotes = !inQuotes;
|
|
}
|
|
} else if (char === ',' && !inQuotes) {
|
|
currentLine.push(currentField.trim());
|
|
currentField = '';
|
|
} else if ((char === '\n' || char === '\r') && !inQuotes) {
|
|
if (char === '\r' && nextChar === '\n') {
|
|
i++;
|
|
}
|
|
if (currentField || currentLine.length > 0) {
|
|
currentLine.push(currentField.trim());
|
|
lines.push(currentLine);
|
|
currentLine = [];
|
|
currentField = '';
|
|
}
|
|
} else {
|
|
currentField += char;
|
|
}
|
|
}
|
|
|
|
if (currentField || currentLine.length > 0) {
|
|
currentLine.push(currentField.trim());
|
|
lines.push(currentLine);
|
|
}
|
|
|
|
return lines;
|
|
};
|
|
|
|
const parsed = parseCsv(text);
|
|
|
|
if (parsed.length === 0) {
|
|
alert('CSV 파일이 비어있습니다.');
|
|
return;
|
|
}
|
|
|
|
// 첫 번째 줄을 헤더로 사용
|
|
const headers = parsed[0];
|
|
const rows = parsed.slice(1);
|
|
|
|
setCsvHeaders(headers);
|
|
setCsvRows(rows);
|
|
setCsvData(parsed);
|
|
} catch (parseError) {
|
|
console.error('CSV 파싱 오류:', parseError);
|
|
alert('CSV 파일을 읽는 중 오류가 발생했습니다.');
|
|
}
|
|
};
|
|
|
|
reader.onerror = () => {
|
|
alert('파일을 읽는 중 오류가 발생했습니다.');
|
|
};
|
|
|
|
reader.readAsText(file, 'UTF-8');
|
|
|
|
// 기존 파일이 있으면 확인 모달 표시
|
|
if (questionFileObject || questionFileKey) {
|
|
setPendingFiles([file]);
|
|
setPendingFileType('csv');
|
|
setIsFileReplaceModalOpen(true);
|
|
e.target.value = '';
|
|
return;
|
|
}
|
|
|
|
// 기존 파일이 없으면 바로 업로드
|
|
await handleCsvFileUpload(file);
|
|
} catch (error) {
|
|
console.error('학습 평가 문제 업로드 실패:', error);
|
|
alert('파일 업로드에 실패했습니다. 다시 시도해주세요.');
|
|
}
|
|
// input 초기화 (같은 파일 다시 선택 가능하도록)
|
|
e.target.value = '';
|
|
}}
|
|
/>
|
|
</label>
|
|
</div>
|
|
</div>
|
|
<div className="border border-[#dee1e6] rounded-[8px] bg-gray-50">
|
|
{csvData.length === 0 ? (
|
|
<div className="h-[64px] flex items-center justify-center">
|
|
<p className="text-[14px] font-normal leading-[1.5] text-[#8c95a1] text-center">
|
|
학습 평가용 문항 파일을 첨부해주세요.
|
|
</p>
|
|
</div>
|
|
) : (
|
|
<div className="flex flex-col">
|
|
{/* 파일 정보 및 삭제 버튼 */}
|
|
{questionFileObject && (
|
|
<div className="h-[40px] px-[20px] py-[12px] flex items-center gap-[12px] bg-white border-b border-[#dee1e6]">
|
|
<p className="flex-1 text-[15px] font-normal leading-[1.5] text-[#333c47]">
|
|
{questionFileObject.name}
|
|
</p>
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
setQuestionFileObject(null);
|
|
setQuestionFileKey(null);
|
|
setQuestionFileCount(0);
|
|
setCsvData([]);
|
|
setCsvHeaders([]);
|
|
setCsvRows([]);
|
|
}}
|
|
className="size-[16px] flex items-center justify-center cursor-pointer hover:opacity-70 transition-opacity shrink-0"
|
|
aria-label="파일 삭제"
|
|
>
|
|
<CloseXOSvg />
|
|
</button>
|
|
</div>
|
|
)}
|
|
{/* CSV 표 */}
|
|
<div className="m-[24px] border border-[#dee1e6] border-solid relative bg-white max-h-[400px] overflow-y-auto">
|
|
<div className="content-stretch flex flex-col items-start justify-center relative size-full">
|
|
{/* 헤더 */}
|
|
<div className="bg-[#f1f8ff] content-stretch flex h-[48px] items-center overflow-clip relative shrink-0 w-full sticky top-0 z-10">
|
|
{csvHeaders.map((header, index) => {
|
|
const isLast = index === csvHeaders.length - 1;
|
|
return (
|
|
<div
|
|
key={index}
|
|
className={`border-[#dee1e6] ${
|
|
isLast ? '' : 'border-[0px_1px_0px_0px]'
|
|
} border-solid box-border content-stretch flex gap-[10px] h-full items-center justify-center px-[8px] py-[12px] relative shrink-0 ${
|
|
index === 0 ? 'w-[48px]' : index === 1 ? 'basis-0 grow min-h-px min-w-px' : 'w-[140px]'
|
|
}`}
|
|
>
|
|
<div className="flex flex-col font-['Pretendard:SemiBold',sans-serif] justify-center leading-[0] not-italic relative shrink-0 text-[#4c5561] text-[14px] text-nowrap">
|
|
<p className="leading-[1.5] whitespace-pre">{header || `열 ${index + 1}`}</p>
|
|
</div>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
|
|
{/* 데이터 행 */}
|
|
{csvRows.map((row, rowIndex) => (
|
|
<div
|
|
key={rowIndex}
|
|
className="border-[#dee1e6] border-[1px_0px_0px] border-solid h-[48px] relative shrink-0 w-full"
|
|
>
|
|
<div className="content-stretch flex h-[48px] items-start overflow-clip relative rounded-[inherit] w-full">
|
|
{csvHeaders.map((_, colIndex) => {
|
|
const isLast = colIndex === csvHeaders.length - 1;
|
|
const cellValue = row[colIndex] || '';
|
|
return (
|
|
<div
|
|
key={colIndex}
|
|
className={`border-[#dee1e6] ${
|
|
isLast ? '' : 'border-[0px_1px_0px_0px]'
|
|
} border-solid box-border content-stretch flex flex-col gap-[4px] items-center justify-center px-[8px] py-[12px] relative shrink-0 ${
|
|
colIndex === 0 ? 'w-[48px]' : colIndex === 1 ? 'basis-0 grow min-h-px min-w-px' : 'w-[140px]'
|
|
}`}
|
|
>
|
|
<p className="font-['Pretendard:Medium',sans-serif] leading-[1.5] not-italic relative shrink-0 text-[#1b2027] text-[15px] text-nowrap whitespace-pre">
|
|
{cellValue}
|
|
</p>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{/* 액션 버튼 */}
|
|
<div className="flex items-center justify-end gap-[12px]">
|
|
<button
|
|
type="button"
|
|
onClick={handleBackClick}
|
|
className="h-[48px] px-[8px] rounded-[10px] bg-[#f1f3f5] text-[16px] font-semibold leading-[1.5] text-[#4c5561] min-w-[80px] hover:bg-[#e5e7eb] transition-colors cursor-pointer"
|
|
>
|
|
취소
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={handleSaveClick}
|
|
className="h-[48px] px-[16px] rounded-[10px] bg-[#1f2b91] text-[16px] font-semibold leading-[1.5] text-white hover:bg-[#1a2478] transition-colors cursor-pointer"
|
|
>
|
|
저장하기
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
) : (
|
|
/* 목록 모드 */
|
|
<>
|
|
{/* 제목 영역 */}
|
|
<div className="h-[100px] flex items-center">
|
|
<h1 className="text-[24px] font-bold leading-[1.5] text-[#1b2027]">
|
|
강좌 관리
|
|
</h1>
|
|
</div>
|
|
|
|
{/* 헤더 영역 (제목과 콘텐츠 사이) */}
|
|
<div className="pt-2 pb-4 flex items-center justify-between">
|
|
<p className="text-[15px] font-medium leading-[1.5] text-[#333c47] whitespace-nowrap">
|
|
총 {totalCount}건
|
|
</p>
|
|
<button
|
|
type="button"
|
|
onClick={handleRegisterClick}
|
|
className="h-[40px] px-4 rounded-[8px] bg-[#1f2b91] text-[16px] font-semibold leading-[1.5] text-white whitespace-nowrap hover:bg-[#1a2478] transition-colors cursor-pointer"
|
|
>
|
|
등록하기
|
|
</button>
|
|
</div>
|
|
|
|
{/* 콘텐츠 영역 */}
|
|
<div className="flex-1 pt-2 flex flex-col">
|
|
{lessons.length === 0 ? (
|
|
<div className="rounded-lg border border-[#dee1e6] bg-white min-h-[400px] flex items-center justify-center">
|
|
<p className="text-[16px] font-medium leading-[1.5] text-[#333c47]">
|
|
<span className="block text-center">
|
|
등록된 강좌가 없습니다.
|
|
<br />
|
|
강좌를 등록해주세요.
|
|
</span>
|
|
</p>
|
|
</div>
|
|
) : (
|
|
<>
|
|
<div className="rounded-[8px]">
|
|
<div className="w-full rounded-[8px] border border-[#dee1e6] overflow-visible">
|
|
<table className="min-w-full border-collapse">
|
|
<colgroup>
|
|
<col />
|
|
<col />
|
|
<col />
|
|
<col style={{ width: 140 }} />
|
|
<col style={{ width: 120 }} />
|
|
<col style={{ width: 120 }} />
|
|
</colgroup>
|
|
<thead>
|
|
<tr className="h-12 bg-gray-50 text-left">
|
|
<th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]">교육과정명</th>
|
|
<th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]">강좌명</th>
|
|
<th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]">첨부파일</th>
|
|
<th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]">학습 평가 문제 수</th>
|
|
<th className="border-r border-[#dee1e6] px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]">등록자</th>
|
|
<th className="px-4 text-[14px] font-semibold leading-[1.5] text-[#4c5561]">등록일</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{paginatedLessons.map((lesson) => {
|
|
// 원본 강좌 데이터 찾기
|
|
const rawLecture = rawLecturesRef.current.find(
|
|
(l: any) => String(l.id || l.lectureId) === lesson.id
|
|
);
|
|
|
|
return (
|
|
<tr
|
|
key={lesson.id}
|
|
onClick={() => {
|
|
// 원본 데이터를 sessionStorage에 저장
|
|
if (rawLecture) {
|
|
sessionStorage.setItem('selectedLecture', JSON.stringify(rawLecture));
|
|
}
|
|
router.push(`/admin/lessons/${lesson.id}`);
|
|
}}
|
|
className="h-12 hover:bg-[#F5F7FF] transition-colors cursor-pointer"
|
|
>
|
|
<td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
|
|
{lesson.courseName}
|
|
</td>
|
|
<td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
|
|
{lesson.lessonName}
|
|
</td>
|
|
<td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027]">
|
|
{lesson.attachments}
|
|
</td>
|
|
<td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
|
|
{lesson.questionCount}개
|
|
</td>
|
|
<td className="border-t border-r border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
|
|
{lesson.createdBy}
|
|
</td>
|
|
<td className="border-t border-[#dee1e6] px-4 text-[13px] leading-[1.5] text-[#1b2027] whitespace-nowrap">
|
|
{lesson.createdAt}
|
|
</td>
|
|
</tr>
|
|
);
|
|
})}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
|
|
{/* 페이지네이션 - 10개 초과일 때만 표시 */}
|
|
{lessons.length > ITEMS_PER_PAGE && (() => {
|
|
// 페이지 번호를 10단위로 표시
|
|
const pageGroup = Math.floor((currentPage - 1) / 10);
|
|
const startPage = pageGroup * 10 + 1;
|
|
const endPage = Math.min(startPage + 9, totalPages);
|
|
const visiblePages = Array.from({ length: endPage - startPage + 1 }, (_, i) => startPage + i);
|
|
|
|
return (
|
|
<div className="pt-8 pb-[32px] flex items-center justify-center">
|
|
<div className="flex items-center justify-center gap-[8px]">
|
|
{/* First (맨 앞으로) */}
|
|
<button
|
|
type="button"
|
|
onClick={() => setCurrentPage(1)}
|
|
aria-label="맨 앞 페이지"
|
|
className="flex items-center justify-center rounded-[1000px] p-[8.615px] size-[32px] text-[#333c47] disabled:opacity-40 cursor-pointer disabled:cursor-not-allowed"
|
|
disabled={currentPage === 1}
|
|
>
|
|
<div className="relative flex items-center justify-center w-full h-full">
|
|
<ChevronDownSvg width={14.8} height={14.8} className="rotate-90 absolute left-[2px]" />
|
|
<ChevronDownSvg width={14.8} height={14.8} className="rotate-90 absolute right-[2px]" />
|
|
</div>
|
|
</button>
|
|
|
|
{/* Prev */}
|
|
<button
|
|
type="button"
|
|
onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
|
|
aria-label="이전 페이지"
|
|
className="flex items-center justify-center rounded-[1000px] p-[8.615px] size-[32px] text-[#333c47] disabled:opacity-40 cursor-pointer disabled:cursor-not-allowed"
|
|
disabled={currentPage === 1}
|
|
>
|
|
<ChevronDownSvg width={14.8} height={14.8} className="rotate-90" />
|
|
</button>
|
|
|
|
{/* Numbers */}
|
|
{visiblePages.map((n) => {
|
|
const active = n === currentPage;
|
|
return (
|
|
<button
|
|
key={n}
|
|
type="button"
|
|
onClick={() => setCurrentPage(n)}
|
|
aria-current={active ? 'page' : undefined}
|
|
className={[
|
|
'flex items-center justify-center rounded-[1000px] size-[32px] cursor-pointer',
|
|
active ? 'bg-[#ecf0ff]' : 'bg-white',
|
|
].join(' ')}
|
|
>
|
|
<span className="text-[16px] leading-[1.4] text-[#333c47]">{n}</span>
|
|
</button>
|
|
);
|
|
})}
|
|
|
|
{/* Next */}
|
|
<button
|
|
type="button"
|
|
onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
|
|
aria-label="다음 페이지"
|
|
className="flex items-center justify-center rounded-[1000px] p-[8.615px] size-[32px] text-[#333c47] disabled:opacity-40 cursor-pointer disabled:cursor-not-allowed"
|
|
disabled={currentPage === totalPages}
|
|
>
|
|
<ChevronDownSvg width={14.8} height={14.8} className="-rotate-90" />
|
|
</button>
|
|
|
|
{/* Last (맨 뒤로) */}
|
|
<button
|
|
type="button"
|
|
onClick={() => setCurrentPage(totalPages)}
|
|
aria-label="맨 뒤 페이지"
|
|
className="flex items-center justify-center rounded-[1000px] p-[8.615px] size-[32px] text-[#333c47] disabled:opacity-40 cursor-pointer disabled:cursor-not-allowed"
|
|
disabled={currentPage === totalPages}
|
|
>
|
|
<div className="relative flex items-center justify-center w-full h-full">
|
|
<ChevronDownSvg width={14.8} height={14.8} className="-rotate-90 absolute left-[2px]" />
|
|
<ChevronDownSvg width={14.8} height={14.8} className="-rotate-90 absolute right-[2px]" />
|
|
</div>
|
|
</button>
|
|
</div>
|
|
</div>
|
|
);
|
|
})()}
|
|
</>
|
|
)}
|
|
</div>
|
|
</>
|
|
)}
|
|
</div>
|
|
</main>
|
|
</div>
|
|
</div>
|
|
|
|
{/* 강좌 등록 완료 토스트 */}
|
|
{showToast && (
|
|
<div className="fixed right-[60px] bottom-[60px] z-50">
|
|
<div className="bg-white border border-[#dee1e6] rounded-[8px] p-4 min-w-[360px] flex gap-[10px] items-center">
|
|
<div className="relative shrink-0 w-[16.667px] h-[16.667px]">
|
|
<svg width="17" height="17" viewBox="0 0 17 17" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
<circle cx="8.5" cy="8.5" r="8.5" fill="#384FBF"/>
|
|
<path d="M5.5 8.5L7.5 10.5L11.5 6.5" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
|
|
</svg>
|
|
</div>
|
|
<p className="text-[15px] font-medium leading-[1.5] text-[#1b2027] text-nowrap">
|
|
{toastMessage}
|
|
</p>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{/* 파일 교체 확인 모달 */}
|
|
{isFileReplaceModalOpen && (
|
|
<div className="fixed inset-0 z-[60] flex items-center justify-center">
|
|
<div
|
|
className="absolute inset-0 bg-black/40"
|
|
onClick={handleFileReplaceCancel}
|
|
aria-hidden="true"
|
|
/>
|
|
<div className="relative z-10 bg-white rounded-[8px] p-[24px] shadow-[0px_8px_20px_0px_rgba(0,0,0,0.06),0px_24px_60px_0px_rgba(0,0,0,0.12)] flex flex-col gap-[32px] items-end justify-end min-w-[500px]">
|
|
<div className="flex flex-col gap-[16px] items-start justify-center w-full">
|
|
<div className="flex gap-[8px] items-start w-full">
|
|
<p className="text-[18px] font-semibold leading-[1.5] text-[#333c47]">
|
|
이미 첨부된 파일이 있습니다.
|
|
</p>
|
|
</div>
|
|
<div className="flex gap-[8px] items-start w-full">
|
|
<div className="text-[15px] font-normal leading-[1.5] text-[#4c5561]">
|
|
<p className="mb-0">새 파일을 첨부하면 기존 파일이 삭제됩니다.</p>
|
|
<p>계속 진행하시겠습니까?</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div className="flex gap-[8px] items-center justify-end shrink-0">
|
|
<button
|
|
type="button"
|
|
onClick={handleFileReplaceCancel}
|
|
className="bg-[#f1f3f5] h-[40px] rounded-[8px] px-[8px] flex items-center justify-center shrink-0 w-[80px] hover:bg-[#e9ecef] cursor-pointer transition-colors"
|
|
>
|
|
<p className="text-[16px] font-semibold leading-[1.5] text-[#4c5561] text-center whitespace-pre">
|
|
취소
|
|
</p>
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={handleFileReplaceConfirm}
|
|
className="bg-[#1f2b91] h-[40px] rounded-[8px] px-[8px] flex items-center justify-center shrink-0 w-[80px] hover:bg-[#1a2478] cursor-pointer transition-colors"
|
|
>
|
|
<p className="text-[16px] font-semibold leading-[1.5] text-white text-center whitespace-pre">
|
|
확인
|
|
</p>
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|