Files
frontend/apps/sn/app/(map-layout)/map/components/searchModalReportApi.ts
T

123 lines
2.8 KiB
TypeScript

import {useState, useEffect} from 'react';
import { getDcData } from '@/components/lib/api';
import moment from "moment";
const ADDR_URL = process.env.NEXT_PUBLIC_ADDR_URL;
export type SelectDataType = {
val: string;
text: string;
sido?: string; // 시도 코드
};
type Folder = {
fldrSn: string;
upFldrSn: string;
fldrNm: string;
sort_seq: number;
children: Folder[];
};
type FlattenedFolder = {
[key: string]: string;
};
// 시군구 데이터
const getSggCd = async (): Promise<SelectDataType[]> => {
try {
const response = await fetch(`${ADDR_URL}/api/v1/addr/sgg`, { method: "GET", headers: { accept: "application/json" } });
if (!response.ok) throw new Error(`시군구 데이터 오류: ${response.status}`);
const res = await response.json();
const sgg = res.data;
const sggCd = sgg.map((item: any) => ({
val: item.adstDstrCd,
sido: item.sido,
text: item.gugun,
}));
sggCd.unshift({ val: '0', text: '전체' }); // "전체" 옵션 추가
return sggCd;
} catch (error) {
console.error('시군구 데이터를 가져오는데 실패했습니다:', error);
return [{ val: '0', text: '전체', sido: '0' }];
}
};
export const useSggCd = () => {
const [data, setData] = useState<SelectDataType[]>([]);
useEffect(() => {
const fetch = async () => {
const result = await getSggCd();
if (result) {
setData(result);
}
};
fetch();
}, []);
return data;
};
const isYear = (value: string): boolean => {
return /^[0-9]{4}년$/.test(value);
};
function flattenFolders(data: Folder[]): FlattenedFolder[] {
const result: FlattenedFolder[] = [];
const sggCd = await getSggCd();
function traverse(
node: Folder,
path: { [key: string]: string },
level: number
) {
if (level === 2) {
if (!sggCd.some(item => item.text === node.fldrNm)) {
}
if (isYear(node.fldrNm)) {
level++;
}
}
const newPath = {
...path,
//[`level${level}_fldrSn`]: node.fldrSn,
[`level${level}`]: node.fldrNm,
};
if (node.children.length === 0) {
result.push(newPath);
} else {
node.children.forEach((child) => {
traverse(child, newPath, level + 1);
});
}
}
data.forEach((root) => traverse(root, {}, 0));
return result;
}
export const useDcTree = () => {
const [data, setData] = useState<FlattenedFolder[]>([]);
useEffect(() => {
const fetch = async () => {
const result = await getDcData(`/api/v1/dc/tree`);
if (result) {
const flattenedData = flattenFolders(result);
setData(flattenedData);
}
};
fetch();
}, []);
return data;
};
export const getDcTree = async () => {
const queryString = '';
const result = await getDcData(`/api/v1/dc/tree${queryString ? `?${queryString}` : ''}`);
return result;
};