"use client"; import { ChevronDown } from "lucide-react"; import { useParams, useRouter } from "next/navigation"; import { useEffect, useRef, useState } from "react"; import { KriBarChart } from "@/components/chart"; import { AppPageTitle } from "@/components/app-shell/AppPageTitle"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { CHART_BAR_MAX_WIDTH, CHART_FONT_SIZE, CHART_HEIGHT } from "@/const/epolicy-dash.const"; import { cn } from "@/lib/utils"; import { toChartData } from "@/lib/chart-utils"; import { formatDecimal1, formatThousands, round1 } from "@/lib/format"; import { isSessionInvalid, resolveApiErrorMessage } from "@/lib/api-error-message"; import { usePartDetailQuery } from "@/query/waves"; import type { Item, ResultGroup } from "@/types/wave"; // audience.type이 SURVEY인 문항의 대표 색상은 실제 응답에 포함된 series[].color를 그대로 사용한다. // surveyCd/label 기준으로 색상을 별도 매핑하지 않는다. function findAudienceColor(item: Item): string | undefined { for (const group of item.resultGroups) { const withColor = group.series.find((series) => series.color); if (withColor) return withColor.color; } return undefined; } function seriesLegendName(label: string, baseCount: number | null) { return baseCount === null ? label : `${label} (N=${formatThousands(baseCount)})`; } // 차트에서 숨겨진(chartVisible=false) 카테고리를 각주로 만든다. 값이 0인 항목은 무시한다. // 시리즈(설문)가 하나뿐이면 "※ 기타 0.9%, 모름·무응답 2.3%"처럼 시리즈명을 생략하고, // 여러 개면 "※ 기타 : 일반국민 0.9%, 전문가 3.8% | 모름·무응답 : 일반국민 2.5%"처럼 구분해서 표기한다. function buildHiddenCategoryNote(group: ResultGroup): string | null { const isSingleSeries = group.series.length === 1; const parts = group.categories .map((category, index) => { if (category.chartVisible) return null; const entries = group.series .map((series) => ({ label: series.label, value: series.values[index] })) .filter((entry) => entry.value !== 0); if (!entries.length) return null; if (isSingleSeries) { return `${category.label} ${formatDecimal1(entries[0].value)}%`; } const valueText = entries.map((entry) => `${entry.label} ${formatDecimal1(entry.value)}%`).join(", "); return `${category.label} : ${valueText}`; }) .filter((part): part is string => part !== null); if (!parts.length) return null; return `※ ${parts.join(isSingleSeries ? ", " : " | ")}`; } // x축 카테고리 라벨 폭을 컨테이너 실측 폭 기준으로 계산한다(카테고리당 슬롯 폭에 여유를 둔 값). // 고정값을 쓰면 화면이 넓을 때는 불필요하게 줄바꿈되고, 좁을 때는 라벨이 겹치는 문제가 생긴다. const MIN_AXIS_LABEL_WIDTH = 48; function ResultGroupChart({ group }: { group: ResultGroup }) { const chartData = toChartData(group.categories, group.series); const hasChartData = chartData.categories.length > 0 && chartData.series.length > 0; const chartWrapperRef = useRef(null); const [axisLabelWidth, setAxisLabelWidth] = useState(); useEffect(() => { const el = chartWrapperRef.current; if (!el || chartData.categories.length === 0) return; const updateAxisLabelWidth = () => { const width = (el.clientWidth / chartData.categories.length) * 0.85; setAxisLabelWidth(Math.max(MIN_AXIS_LABEL_WIDTH, width)); }; updateAxisLabelWidth(); const observer = new ResizeObserver(updateAxisLabelWidth); observer.observe(el); return () => observer.disconnect(); }, [chartData.categories.length]); if (!hasChartData) return null; return (
({ name: seriesLegendName(item.label, item.baseCount), data: item.values.map(round1), color: item.color, option: { label: { show: true, position: "top", fontSize: CHART_FONT_SIZE, formatter: (params: { value: number }) => formatDecimal1(params.value), }, }, }))} legend={{ left: 0, top: 0, textStyle: { fontSize: CHART_FONT_SIZE } }} grid={{ top: 55, right: 25, bottom: 5, left: 0, containLabel: true }} xAxis={{ axisLabel: { fontSize: CHART_FONT_SIZE, interval: 0, ...(axisLabelWidth ? { width: axisLabelWidth, overflow: "break" as const } : {}), }, }} yAxis={{ min: 0, max: 100, interval: 25, axisLabel: { fontSize: CHART_FONT_SIZE } }} barMaxWidth={CHART_BAR_MAX_WIDTH} height={CHART_HEIGHT} />
); } function ResultGroupTable({ group }: { group: ResultGroup }) { if (!group.categories.length) { return

데이터가 없습니다.

; } return (
{`BASE: ${group.series[0].baseText}`} 사례수 {group.categories.map((category) => ( {category.label} ))} {group.series.map((series) => ( {series.label} {series.baseCount !== null ? `(${formatThousands(series.baseCount)})` : "-"} {series.values.map((value, index) => ( {value === 0 ? "-" : formatDecimal1(value)} ))} ))}
); } function ItemCard({ item }: { item: Item }) { const [showTable, setShowTable] = useState(false); const [activeGroupIndex, setActiveGroupIndex] = useState(0); const hasSubItems = item.resultGroups.some((group) => group.subItem !== null); const activeGroup = item.resultGroups[activeGroupIndex] ?? item.resultGroups[0]; const hiddenCategoryNote = activeGroup ? buildHiddenCategoryNote(activeGroup) : null; return (

{item.title}

{item.audience.label}
{hasSubItems ? (
{item.resultGroups.map((group, index) => ( ))}
) : null} {activeGroup ? (
{hiddenCategoryNote ?

{hiddenCategoryNote}

: null} {showTable ? (
) : null}
) : null} {item.comment ?

{item.comment}

: null}
); } export default function PartDetailPage() { const params = useParams<{ waveCd: string; partCd: string }>(); const router = useRouter(); const waveCd = Number(params.waveCd); const partCd = Number(params.partCd); const { data, isPending, isError, error } = usePartDetailQuery(waveCd, partCd); useEffect(() => { if (isError && isSessionInvalid(error)) router.replace("/logout"); }, [isError, error, router]); if (isPending) { return

불러오는 중입니다...

; } if (isError) { if (isSessionInvalid(error)) return null; return (

{resolveApiErrorMessage(error)}

); } return (
{data.items.map((item) => ( ))}
); }