Files
frontend/apps/st/src/components/statistics/total/WaterReuseTot.tsx
T

230 lines
11 KiB
TypeScript

import { useRef, useState } from "react";
import { useAlertStore } from "@/shared/lib";
import { LoadingWithAnimation, Tabs, TabsContent, TabsList, TabsTrigger } from "@common/components";
import SearchForm from "../../module/SearchForm";
import DataGrid from "@/components/module/DataGrid";
import type { ColumnInfo } from "@/components/type/DataGrid.type";
import type { SearchFormValues } from "@/components/type/SearchForm.type";
import { toGridRows } from "@/components/util/grid/gridFunction";
// [폴더 정밀 정비 완료] 프로젝트 트리 구조 5개 컬럼 스펙 패키지 호출
import { SewerageReuseTab1ColumnConfig } from "@/components/util/column/total/sewerageReuse/SewerageReuseTab1Column";
import { SewerageGrayWaterTab2ColumnConfig } from "@/components/util/column/total/sewerageReuse/SewerageGrayWaterTab2Column";
import { SewerageRainwaterTab3ColumnConfig } from "@/components/util/column/total/sewerageReuse/SewerageRainwaterTab3Column";
import { SewerageWwtRtlztnRegTab4ColumnConfig } from "@/components/util/column/total/sewerageReuse/SewerageWwtRtlztnRegTab4Column";
import { SewerageWwtRtlztnSncnTab5ColumnConfig } from "@/components/util/column/total/sewerageReuse/SewerageWwtRtlztnSncnTab5Column";
// 집계표(TOTAL) API 서비스 및 인터페이스 명세 임포트
import { statisticsTotalStatusApi } from "@/entities/statistics/api/statistics-total-service";
import type {
WaterReuseSummaryRequest
} from "@/entities/statistics/model/statistics-total/statistics-sewerage-reuse-total-interface";
import CellColorInfo from "./CellColorInfo";
// 5개 멀티 탭 매핑을 위한 설정 취합 배열
const WaterReuseColumnListTot = [
SewerageReuseTab1ColumnConfig,
SewerageGrayWaterTab2ColumnConfig,
SewerageRainwaterTab3ColumnConfig,
SewerageWwtRtlztnRegTab4ColumnConfig,
SewerageWwtRtlztnSncnTab5ColumnConfig // 👈 5번째 탭 풀장착 완료
];
const firstTabKey = WaterReuseColumnListTot[0]?.tabKey ?? "ST00040007_1";
const WaterReuseTot = () => {
const { setMessage: alert } = useAlertStore((state) => state);
// Map 데이터 구조를 사용하여 완벽하게 안전한 멀티 탭 데이터 상태 유지
const [rowDataMap, setRowDataMap] = useState<Map<string, Record<string, string | number>[]>>(new Map());
const [isLoading, setIsLoading] = useState(false);
const [activeTab, setActiveTab] = useState(firstTabKey);
const lastSearchedValuesRef = useRef<SearchFormValues | null>(null);
const columnInfo = WaterReuseColumnListTot;
const handleReset = () => {
setRowDataMap(new Map());
setActiveTab(firstTabKey);
lastSearchedValuesRef.current = null;
};
const loadGridData = async (tabKey: string, values: SearchFormValues): Promise<boolean> => {
const param: WaterReuseSummaryRequest = {
ctpvNm: values.sido === "ALL" ? "" : values.sido,
sggNm: values.gugun === "ALL" ? "" : values.gugun,
sewerBzmnCd: values.bsnmCd,
statsYr: values.year,
rowDataYn: values.isDetail,
summaryYn: values.isSummary !== 'ALL',
summaryYearCnt: values.isSummary !== 'ALL' ? Number(values.isSummary) : undefined
};
try {
// [TAB1] 공공하수처리수 재이용 현황 조회
if (tabKey === "ST00100001") {
const response = await statisticsTotalStatusApi.getSewerageReuseTab1List(param);
if (response && response.status === "success" && response.data) {
setRowDataMap((prev) => new Map(prev).set(tabKey, toGridRows(response.data as object[])));
return true;
}
alert(response?.message || "데이터 조회 중 오류가 발생했습니다.");
}
// [TAB2] 중수도 현황 조회
if (tabKey === "ST00100002") {
const response = await statisticsTotalStatusApi.getGrayWaterStatusTab2List(param);
if (response && response.status === "success" && response.data) {
setRowDataMap((prev) => new Map(prev).set(tabKey, toGridRows(response.data as object[])));
return true;
}
alert(response?.message || "데이터 조회 중 오류가 발생했습니다.");
}
// [TAB3] 빗물이용시설현황 조회
if (tabKey === "ST00100003") {
const response = await statisticsTotalStatusApi.getRainwaterStatusTab3List(param);
if (response && response.status === "success" && response.data) {
setRowDataMap((prev) => new Map(prev).set(tabKey, toGridRows(response.data as object[])));
return true;
}
alert(response?.message || "데이터 조회 중 오류가 발생했습니다.");
}
// [TAB4] 하·폐수처리수 재이용시설 시공업 등록현황 조회
if (tabKey === "ST00100004") {
const response = await statisticsTotalStatusApi.getWwtRtlztnRegStatusTab4List(param);
if (response && response.status === "success" && response.data) {
setRowDataMap((prev) => new Map(prev).set(tabKey, toGridRows(response.data as object[])));
return true;
}
alert(response?.message || "데이터 조회 중 오류가 발생했습니다.");
}
// [TAB5] 하·폐수처리수 재이용시설 시공업 인가현황 조회
if (tabKey === "ST00100005") {
const response = await statisticsTotalStatusApi.getWwtRtlztnSncnStatusTab5List(param);
if (response && response.status === "success" && response.data) {
setRowDataMap((prev) => new Map(prev).set(tabKey, toGridRows(response.data as object[])));
return true;
}
alert(response?.message || "데이터 조회 중 오류가 발생했습니다.");
}
return false;
} catch {
alert("서버 연결 중 오류가 발생했습니다.");
return false;
}
};
const handleSearch = async (values: SearchFormValues) => {
try {
setIsLoading(true);
const ok = await loadGridData(activeTab, values);
if (ok) {
lastSearchedValuesRef.current = values;
} else {
lastSearchedValuesRef.current = null;
}
} catch {
alert("데이터 조회 중 오류가 발생했습니다.");
lastSearchedValuesRef.current = null;
} finally {
setIsLoading(false);
}
};
const handleActiveTabChange = async (tabKey: string) => {
setActiveTab(tabKey);
const values = lastSearchedValuesRef.current;
if (!values) return;
// 중복 API 통신 방지 필터 캐싱 디스패치
const existing = rowDataMap.get(tabKey);
if (existing && existing.length > 0) return;
try {
setIsLoading(true);
await loadGridData(tabKey, values);
} catch {
alert("데이터 조회 중 오류가 발생했습니다.");
} finally {
setIsLoading(false);
}
};
return (
<div className="relative">
<SearchForm isDetail={true} isSummary={true} onSubmit={handleSearch} onReset={handleReset} sidoSelectText="전체" />
{/* 정중앙 5rem 크기 고정 격리형 로딩 애니메이션 */}
{isLoading && (
<div className="absolute inset-0 z-50 [data-theme='black']:bg-transparent rounded-lg p-10 flex justify-center items-center">
<div className="relative size-[5rem]">
<LoadingWithAnimation color="primary" />
</div>
</div>
)}
<CellColorInfo />
<div className="flex flex-col gap-[0.6rem] mx-[0.6rem]">
<Tabs value={activeTab} onValueChange={(v) => void handleActiveTabChange(v)} className="w-full" variant="default">
<TabsList>
{columnInfo.map((info) => (
<TabsTrigger key={info.tabKey} value={info.tabKey}>
{info.tabLabel}
</TabsTrigger>
))}
</TabsList>
{columnInfo.map((info) => {
const tabKey = info.tabKey;
const rowData = rowDataMap.get(tabKey) ?? [];
const gridColumnInfo: ColumnInfo = {
columns: info.columns,
columnLayout: info.columnLayout,
};
return (
<TabsContent key={tabKey} value={tabKey}>
<DataGrid
columnInfo={gridColumnInfo}
rowStartNum={info.rowStartNum}
excelExportFileSuffix={info.tabLabel}
rowData={rowData}
setRowData={(updater) => {
setRowDataMap((prev) => {
const next = new Map(prev);
const cur = next.get(tabKey) ?? [];
const n = typeof updater === "function" ? updater(cur) : updater;
next.set(tabKey, n);
return next;
});
}}
isExcelImport={false}
isExcelExport={true}
showHeaderCheckbox={false}
fixedColumns={info.fixedColumns}
enableSort={false}
cellStyleCallback={({ row }) => {
const rowType = String(row.rowType ?? '');
if (rowType === 'DETAIL') return undefined;
if (rowType === 'BIZ_SUM') return 'rg-cell-rowtype-biz-sum';
if (rowType === 'SUMMARY') return 'rg-cell-rowtype-summary';
return 'rg-cell-rowtype-other';
}}
/>
</TabsContent>
);
})}
</Tabs>
</div>
</div>
);
};
export default WaterReuseTot;