import { getDcData } from '@/components/lib/api'; import { fileDownload } from '@/utils'; import { useReportTabStore } from '@/store/useReportTabStore'; import useSearchModalStore from '@/app/store/useSearchModalStore'; export type Folder = { clsfSystmSn: string; upClsfSystmSn: string; clsfSystmNm: string; children: Folder[]; }; export type FlattenedFolder = { [key: string]: string | number | undefined; }; export type SelectDataType = { text: string; val: string; sido?: string; // 시도 코드 (선택 사항) } export type ReportDataFile = { no: number; fileTitle: string; regDt: string; fileSn: string; filePath: string; } export default function useReportTab() { const REPORT_TYPES = [ { val: '0', text: '전체' }, { val: '1', text: '보고서' }, { val: '2', text: '요약보고서' }, { val: '3', text: '부록' }, { val: '4', text: '기타' } ]; const { curPage, setIsLoading } = useSearchModalStore(); const { dcFiles: filesOrigin, files, setFiles } = useReportTabStore(); /** * Flatten a hierarchical folder structure into a flat array. * @param data - The hierarchical folder data to flatten. * @returns An array of flattened folders with their paths and levels. */ const flattenFolders = (data: Folder[]): FlattenedFolder[] => { const result: FlattenedFolder[] = []; const exceptNodeNm = ["부분", "통합", "전체"]; const addNodeNm = ["보고서", "요약보고서", "부록", "기타"]; // level5 const columnNms: { [key: number]: string } = { 0: "root", 1: "sido", 2: "sigungu", 3: "approvalYear" , 4: "plantZoneGubun", 5: "reportGubun", 7: "fileName", 8: "regDate" }; const traverse = ( node: Folder, path: { [key: string]: string | number }, level: number ) => { const isYear = (value: string): boolean => { return /^[0-9]{4}년$/.test(value); }; if (level === 2 && isYear(node.clsfSystmNm)) { level++; } if (level === 4 && addNodeNm.includes(node.clsfSystmNm)) { level++; // 레벨을 증가시켜 하위값에 추가되도록 함. } const newPath = { ...path, [`${columnNms[level]}`]: node.clsfSystmNm, }; if (node.children.length === 0) { newPath.no = result.length + 1; newPath.clsfSystmSn = node.clsfSystmSn; // 파일 조회를 위한 고유번호 result.push(newPath); } else { if (level === 4) { if (exceptNodeNm.includes(node.clsfSystmNm)) { level--; // 제외할 노드 이름인 경우, 현재의 레벨에 하위값이 써지도록 함. } } node.children.forEach((child) => { traverse(child, newPath, level + 1); }); } } if (data && data.length > 0 && data[0]?.clsfSystmNm == "기본계획") { // data가 비어있지 않고 children이 있는 경우에만 처리 data.forEach((root) => traverse(root, {}, 0)); } else { data.forEach((root) => traverse(root, {}, 1)); } return result; } const getDcFiles = async (clsfSystmSn: string): Promise => { if (!clsfSystmSn) { console.error("clsfSystmSn is required to get files."); return []; } const queryString = 'clsfSystmSn=' + clsfSystmSn; const result = await getDcData(`/api/v1/dc/file${queryString ? `?${queryString}` : ''}`); return result; }; // 파일 이름 추가 const addFileName = async (data: FlattenedFolder[]) => { const fileReportData = await Promise.all( data.map(async (item) => { const fileArr: ReportDataFile[] = await getDcFiles(String(item.clsfSystmSn)); let result: FlattenedFolder; if (fileArr.length > 0) { const f = fileArr[0]; const fCount = fileArr.length; result = { ...item, fileName: f?.fileTitle + " 외 " + fCount + "건", regDate: f?.regDt, fileSn: f?.fileSn, filePath: f?.filePath }; } else { result = { ...item, fileName: "", regDate: "", fileSn: "", filePath: "" }; } return result; }) ); return fileReportData; }; const getDcFileDownload = async (fileSn: string, fileName: string, filePath: string) => { if (filePath === "") { alert(`filePath 정보가 없으므로 다운로드가 불가합니다.\nfilesn: ${fileSn}`); return; } const queryString = 'filePath=' + encodeURIComponent(filePath); const responseBlob = await getDcData(`/api/v1/dc/file/download${queryString ? `?${queryString}` : ''}`, "blob"); fileDownload(responseBlob, fileName); } // 파일 목록 조회 const getFiles = async () => { setIsLoading(true); // 로딩 시작 try { let data = filesOrigin; data = data?.slice((curPage - 1) * 10, curPage * 10); // paging data = data?.map((item, index) => ({ ...item, no: (curPage - 1) * 10 + index + 1 })); setFiles(data); } catch (error) { console.error("파일 목록 조회 에러:", error); } finally { setIsLoading(false); // 로딩 종료 } }; // cellClick 핸들러 const handleCellClick = (index: number | undefined) => { if (typeof index === "number" && files[index]) { const fileName = files[index].fileTitle; const filePath = files[index].filePath; if (files[index].fileSn !== "") { getDcFileDownload(files[index].fileSn, fileName, filePath); } } }; return { REPORT_TYPES, flattenFolders, addFileName, getDcFiles, getDcFileDownload, getFiles, handleCellClick }; }