Files
frontend/apps/dm/app/(base-layout)/pages/wrStatus/page.tsx
T
2025-12-08 11:17:59 +09:00

388 lines
15 KiB
TypeScript

'use client';
import { regionData, regionIdMap } from '@/app/common/comFunction';
import { useDmStore } from '@/app/store';
import type { DmStatusDataType } from '@/app/store/wrStatus/type';
import { CHART_FORM, MainChart, type ChartConfig } from '@common/business_components';
import React, { useEffect, useRef, useState, useCallback } from 'react';
import { setCookie } from "../../../../src/shared/lib";
setCookie("site-id-key", process.env.NEXT_PUBLIC_SITE_ID || "DM");
interface WrStatusChartProps {
chartForm: string;
chartConfig: ChartConfig;
chartData: any;
chartTitle: string;
chartClassName?: string;
graphSize?: number;
yFieldText? : string | undefined;
yFieldText2? : string | undefined;
showLegend? : boolean;
setXAxisYearTick ?: boolean;
}
export default function WrStatusPage() {
const { Common, dmStatus, getDmStatusData,initializeCommonData} = useDmStore((state) => state);
const { year:defaultYear, statusData,facilityTotals ,chartData} = dmStatus;
const [selectedRegion, setSelectedRegion] = useState<string | null>(null);
const [hoveredRegion, setHoveredRegion] = useState<string | null>(null);
const [tooltipPosition, setTooltipPosition] = useState<{ x: number; y: number } | null>(null);
const [chartOption, setChartOption] = useState<WrStatusChartProps>({} as WrStatusChartProps);
const svgContainerRef = useRef<HTMLDivElement>(null);
const colorLegend = [
{ label: '하수', color: '#FF6B6B', key: 'sewage' },
{ label: '빗물', color: '#4ECDC4', key: 'rainwater' },
{ label: '중수도', color: '#45B7D1', key: 'reclaimed' },
];
const facilityTotalsColor = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FED16A'];
// const [defaultYear, setDefaultYear] = useState<string>("");
// const defaultYear= '2023';
const handleMarkerClick = (regionId: string) => {
if (selectedRegion === regionId) {
setSelectedRegion(null);
} else {
setSelectedRegion(regionId);
}
};
useEffect(() => {
initializeCommonData();
}, [initializeCommonData]);
const createDonutMarker = useCallback((svg: SVGSVGElement, x: number, y: number, name: string, values: number[]) => {
const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FED16A'];
const radius = 26;
const innerRadius = 18;
// const regionId = regionIdMap[name];
const regionId = regionIdMap[name];
if (!regionId) {
console.warn(`Invalid region name: ${name}`);
return;
}
const g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
g.setAttribute('transform', `translate(${x}, ${y})`);
g.setAttribute('id', `marker-${name}`);
g.style.cursor = 'pointer';
g.setAttribute('role', 'button');
g.setAttribute('tabindex', '0');
g.setAttribute('aria-label', `${name} 지역 선택`);
const bg = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
bg.setAttribute('r', radius.toString());
bg.setAttribute('fill', 'white');
bg.setAttribute('pointer-events', 'all');
g.appendChild(bg);
let startAngle = 0;
values.forEach((value, idx) => {
const endAngle = startAngle + value * 2 * Math.PI;
const x1 = radius * Math.sin(startAngle);
const y1 = -radius * Math.cos(startAngle);
const x2 = radius * Math.sin(endAngle);
const y2 = -radius * Math.cos(endAngle);
const largeArc = endAngle - startAngle > Math.PI ? 1 : 0;
const d = `M ${x1} ${y1} A ${radius} ${radius} 0 ${largeArc} 1 ${x2} ${y2} L 0 0 Z`;
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttribute('d', d);
path.setAttribute('fill', colors[idx % colors.length] as string);
g.appendChild(path);
startAngle = endAngle;
});
const center = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
center.setAttribute('r', innerRadius.toString());
center.setAttribute('fill', 'white');
g.appendChild(center);
const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.setAttribute('x', '0');
text.setAttribute('y', '2');
text.setAttribute('text-anchor', 'middle');
text.setAttribute('font-size', '13');
text.setAttribute('font-weight', 'bold');
text.setAttribute('dominant-baseline', 'middle');
text.setAttribute('fill', 'black');
text.textContent = name || '';
g.appendChild(text);
g.addEventListener('mouseenter', (e) => {
setHoveredRegion(regionId);
setTooltipPosition({ x: e.clientX, y: e.clientY });
});
g.addEventListener('mouseleave', () => {
setHoveredRegion(null);
setTooltipPosition(null);
});
g.addEventListener('click', () => {
handleMarkerClick(regionId);
});
g.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
const matrix = g.getScreenCTM();
if (!matrix) return; // 또는 console.warn('matrix is null'); return;
const point = svg.createSVGPoint();
point.x = 0;
point.y = 0;
const transformed = point.matrixTransform(matrix);
setTooltipPosition({ x: transformed.x, y: transformed.y });
setHoveredRegion(regionId);
handleMarkerClick(regionId);
}
});
svg.appendChild(g);
}, [handleMarkerClick, regionIdMap]);
useEffect(() => {
if(Common.selectSidoData&&Common.selectSidoData.length>1) {
getDmStatusData(Common.selectSidoData);
}
},[Common.selectSidoData, getDmStatusData])
useEffect(() => {
const loadSVG = async () => {
try {
const response = await fetch('/img/wrStatus/southKoreaMap.svg');
const svgText = await response.text();
if (svgContainerRef.current) {
svgContainerRef.current.innerHTML = svgText;
const svg = svgContainerRef.current.querySelector('svg') as SVGSVGElement;
if (svg) {
svg.style.width = '58%';
svg.style.height = 'auto';
svg.style.objectFit = 'contain';
// Set default fills
const paths = svg.querySelectorAll('path');
paths.forEach(path => {
if (!path.getAttribute('fill') || path.getAttribute('fill') === 'none') {
path.setAttribute('fill', '#ffffff');
}
});
// Create markers
regionData.forEach(region => {
createDonutMarker(svg, region.x, region.y, region.name, region.values);
});
}
}
} catch (error) {
console.error('SVG 로딩 실패:', error);
if (svgContainerRef.current) {
svgContainerRef.current.innerHTML = "<p className='text-red-500'>SVG 로딩 실패</p>";
}
}
};
loadSVG();
}, [createDonutMarker, regionData]);
useEffect(() => {
const svg = svgContainerRef.current?.querySelector('svg');
if (svg) {
const paths = svg.querySelectorAll('path');
paths.forEach(path => {
const pathId = path.getAttribute('id');
if (pathId) {
if (selectedRegion === pathId) {
path.setAttribute('fill', '#2563eb');
} else {
const original = '#ffffff';
path.setAttribute('fill', original);
}
}
});
}
}, [selectedRegion]);
useEffect(() => {
if(chartData.length>0){
const chartConfig = chartData.reduce((config, element) => {
config[element.label] = {
label: element.label,
color : "hsl(var(--chart-1))"
};
return config;
}, {} as Record<string, { label: string; color: string; }>) satisfies ChartConfig;
const Option = {
chartForm : CHART_FORM.BAR,
chartConfig : chartConfig,
chartData : chartData,
chartTitle : '',
chartClassName : "w-full h-[350px] ",
graphSize : 10,
yFieldText : '시설(개소)',
showLegend : true
}
setChartOption(Option)
}else{
setChartOption({} as WrStatusChartProps)
}
}, [chartData]);
return (
<div className="flex h-screen bg-[#F2F2F2] text-gray-800">
{/* 우측 콘텐츠 영역 */}
<main className="flex-1 p-6 overflow-auto">
{/* 상단 제목 */}
<div className="mb-6 flex justify-between items-center">
<h2 className="text-2xl font-bold">물재이용 현황</h2>
</div>
{/* 콘텐츠 본문 */}
<div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
{/* 지도 카드 */}
<div className="bg-white rounded-xl shadow border border-[#DBE2E6] overflow-hidden max-h-[900px]">
{/* 타이틀 영역 */}
<div className="border-b border-[#DBE2E6] px-4 py-3">
<h3 className="text-[12px] font-semibold">{`재이용시설현황(${defaultYear})`}</h3>
<p className="text-[12px] text-[#999] font-medium">행정구역별 재이용시설현황(개소)</p>
</div>
{/* 본문 콘텐츠 */}
<div className="p-4">
<div className="bg-[#E2EDF3] p-4 rounded shadow relative">
<div className="flex justify-center">
<div
ref={svgContainerRef}
className="w-full max-w-5xl max-h-[680px] overflow-y-auto block mx-auto"
aria-label="대한민국 지역별 재이용시설 분포도"
role="region"
tabIndex={0}
/>
</div>
{typeof window !== 'undefined' && hoveredRegion && tooltipPosition && (
<div
className="fixed bg-white text-[12px] text-gray-700 border border-gray-300 shadow-lg rounded px-3 py-2 z-50"
style={{
top: tooltipPosition.y + 10,
left: tooltipPosition.x + 10,
pointerEvents: 'none',
}}
>
<div className="font-semibold mb-1">{hoveredRegion}</div>
<div className="space-y-1">
{colorLegend.map(({ label, color, key }) => (
<div key={key+'' +color} className="flex items-center space-x-2">
<span className="text-[12px] inline-block w-3 h-3 rounded-sm" style={{ backgroundColor: color }}></span>
<span className="text-[12px]">
{label}:{' '}
{statusData?.find(d => d.region === hoveredRegion)?.[key as keyof DmStatusDataType] || '-'}
</span>
</div>
))}
</div>
</div>
)}
{/* 범례 */}
<div className="absolute bottom-2 right-2 bg-white rounded-lg shadow-md p-4 text-sm space-y-2">
{facilityTotals?.map((item, index) => (
<div key ={'fcltTotal' +index}className="flex items-center space-x-2">
<span className="inline-block w-4 h-4 rounded-sm" style={{backgroundColor:facilityTotalsColor[index]}}></span>
<span className="text-[12px] text-gray-900">{item}</span>
</div>
)) }
</div>
</div>
</div>
</div>
{/* 우측 콘텐츠 (표 + 차트) */}
<div className="col-span-1 flex flex-col space-y-4">
{/* 재이용시설현황 표 */}
<div className="bg-white rounded-xl shadow border border-[#DBE2E6] overflow-hidden">
{/* 타이틀 + 버튼 영역 */}
<div className="flex justify-between items-center border-b border-[#436d85] px-4 py-3">
<div>
<h3 className="text-[12px] font-semibold">{`재이용시설현황(${defaultYear})`}</h3>
<p className="text-[12px] text-[#999] font-medium">행정구역별 재이용시설현황[개소(천m³/년)]</p>
</div>
</div>
<div className="p-4">
<div className="rounded border border-[#DBE2E6] shadow overflow-auto max-h-[292px] p-4">
<table className="min-w-full text-sm text-center">
<caption className="sr-only text-[12px]">행정구역별 하수, 빗물, 중수도, 온배수 재이용시설 수</caption>
<thead className="bg-gray-50 text-xs text-gray-600 uppercase border-b">
<tr>
<th className="text-[12px] font-semibold px-4 py-2">번호</th>
<th className="text-[12px] font-semibold px-4 py-2">시도</th>
<th className="text-[12px] font-semibold px-4 py-2">하수재이용시설</th>
<th className="text-[12px] font-semibold px-4 py-2">빗물이용시설</th>
<th className="text-[12px] font-semibold px-4 py-2">중수도시설</th>
{/* <th className="text-[12px] font-semibold px-4 py-2">하수(이용량,천𝓂³/년)</th>
<th className="text-[12px] font-semibold px-4 py-2">빗물(이용량,천𝓂³/년)</th>
<th className="text-[12px] font-semibold px-4 py-2">중수도(이용량,천𝓂³/년)</th>
<th className="text-[12px] font-semibold px-4 py-2">온배수(이용량,천𝓂³/년)</th> */}
</tr>
</thead>
<tbody className="divide-y">
{statusData?.map((row, index) => (
<tr key={index} className="hover:bg-gray-50">
<td className="text-[12px] px-4 py-2 text-center">
{index+1}
</td>
<td className="text-[12px]">{row.region}</td>
<td className="text-[12px]">{row.sewage}</td>
<td className="text-[12px]">{row.rainwater}</td>
<td className="text-[12px]">{row.reclaimed}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
{/* 재이용통계 차트 */}
<div className="bg-white rounded-xl shadow border border-[#DBE2E6] overflow-hidden">
<div className="border-b border-[#DBE2E6] px-4 py-3">
<h3 className="text-[12px] font-semibold">{`재이용통계(${defaultYear})`}</h3>
<p className="text-[12px] text-[#999] font-medium">행정구역별 재이용시설 현황 개소수 그래프</p>
</div>
<div className="p-4 bg-[#f9fbfd]">
<div className="h-[305px] text-gray-500">
{chartOption?
<MainChart
chartForm={chartOption.chartForm}
chartConfig={chartOption.chartConfig}
chartData={chartOption.chartData?.filter(item=>item.label!= '')}
chartTitle={chartOption.chartTitle}
chartClassName={chartOption.chartClassName}
graphSize={chartOption.graphSize}
yFieldText={chartOption.yFieldText}
showLegend={chartOption.showLegend}
/>
:<></>}
</div>
</div>
</div>
</div>
</div>
</main>
</div>
);
};