"use client"; import React, { useMemo, useState } from "react"; import type { GridComponentOption, LegendComponentOption, TooltipComponentOption, XAXisComponentOption, YAXisComponentOption, SeriesOption, EChartsOption, } from "echarts"; import BaseEChart from "../BaseEChart"; import { buildLgPalette } from "../color"; import { GroupedOverlayBarData, ShowLabel} from "../types"; import {getIsShowLabel, roundedRectIcon} from "@/components/lge-dashboard/chart/utill"; import {AXIS_HIDE_STYLE} from "@/const/lgConst"; type Props = { data: GroupedOverlayBarData; height?: number; tooltip?: TooltipComponentOption; grid?: GridComponentOption; xAxis?: XAXisComponentOption; yAxis?: YAXisComponentOption; legend?: LegendComponentOption; barMaxWidth?: number; showFocusLabel?: ShowLabel; // 연도 legend(좌측) showYearLegend?: boolean; yearTotalColor?: Record; yearFocusColor?: Record; }; const GroupedOverlayBar = ({ data, height = 260, tooltip, grid, xAxis, yAxis, showYearLegend = true, legend, yearTotalColor, yearFocusColor, barMaxWidth, showFocusLabel = "all", }: Props) => { const years = data.years; const totalName = data.totalName ?? "전체"; const focusName = data.focusName ?? "LG"; const yearLabels = useMemo(() => years.map((y) => `${y}년`), [years]); const [yearSelected, setYearSelected] = useState>(() => Object.fromEntries(yearLabels.map((yl) => [yl, true])) ); const option = useMemo(() => { const defaultGrid: EChartsOption["grid"] = {left: 10, right: 10, top: 40, bottom: 10, containLabel: true}; const defaultYAxis: EChartsOption["yAxis"] = { type: "value", ...AXIS_HIDE_STYLE }; const expandedCategories: string[] = []; data.categories.forEach((cat, catIdx) => { years.forEach(year => { expandedCategories.push(`${year}년 ${cat}`); }); // 카테고리 사이에 빈 공간 추가 (마지막 제외) if (catIdx < data.categories.length - 1) { expandedCategories.push(''); // 빈 항목 } }); const defaultXAxis: EChartsOption["xAxis"] = { type: "category", data: expandedCategories, ...AXIS_HIDE_STYLE }; // 연도별 색: 없으면 기본값(전체=회색, LG=빨강 계열) const totalTokens = years.map((y, i) => { const t = yearTotalColor?.[String(y)]; return t ?? (["--lg-gray-200", "--lg-gray-300", "--lg-gray-400", "--lg-gray-500"][i] ?? "--lg-gray-300"); }); const focusTokens = years.map((y, i) => { const t = yearFocusColor?.[String(y)]; return t ?? (["--lg-red-300", "--lg-red-400", "--lg-red-500", "--lg-red-600"][i] ?? "--lg-red-500"); }); const totalColors = buildLgPalette(totalTokens); const focusColors = buildLgPalette(focusTokens); // 연도 legend가 실제로 렌더되려면 "name=24년" series가 있어야 함 (bar가 아닌 line으로) const yearLegendSeries: SeriesOption[] = showYearLegend ? years.map((y, yi) => ({ id: `__year__|${y}`, name: `${y}년`, type: "line", data: [], showSymbol: false, silent: true, tooltip: { show: false }, emphasis: { disabled: true }, lineStyle: { color: focusColors[yi], width: 6 }, itemStyle: { color: focusColors[yi] }, })) : []; const series: SeriesOption[] = []; for (let yi = 0; yi < years.length; yi++) { const year = years[yi]; const yearLabel = `${year}년`; const isOn = yearSelected[yearLabel] !== false; const totalRow = data.total?.[yi] ?? []; const focusRow = data.focus?.[yi] ?? []; // 각 카테고리별로 데이터 배치 const totalData: (number | null)[] = []; const focusData: (number | null)[] = []; data.categories.forEach((cat, ci) => { years.forEach((y, yIdx) => { if (yIdx === yi) { totalData.push(isOn ? (totalRow[ci] ?? null) : null); focusData.push(isOn ? (focusRow[ci] ?? null) : null); } else { totalData.push(null); focusData.push(null); } }); // 카테고리 사이에 null 추가 (마지막 제외) if (ci < data.categories.length - 1) { totalData.push(null); focusData.push(null); } }); // (1) 전체(회색) series.push({ id: `total|${year}`, name: `${year}년-${totalName}`, type: "bar", z: 1, barMaxWidth: 42, emphasis: { disabled: true }, itemStyle: { color: totalColors[yi] }, data: totalData, }); const showLabel = getIsShowLabel(showFocusLabel, yi, years.length); // (2) LG(빨강) - 같은 위치에 겹침 series.push({ id: `focus|${year}`, name: `${year}년-${focusName}`, type: "bar", z: 2, barMaxWidth: 42, barGap: "-100%", emphasis: { disabled: true }, itemStyle: { color: focusColors[yi] }, label: showLabel ? ({ show: true, position: "top", formatter: (p: any) => (p?.value ?? "") as any, } as any) : undefined, data: focusData, }); } const YEAR_ITEM_W = 25; const YEAR_ITEM_H = 14; const YEAR_RADIUS = 4; let yearLegendOpt: LegendComponentOption | undefined = showYearLegend ? ({ top: 0, left: "center", orient: "horizontal", data: yearLabels, selected: yearSelected, icon: roundedRectIcon(YEAR_ITEM_W, YEAR_ITEM_H, YEAR_RADIUS), itemWidth: YEAR_ITEM_W, itemHeight: YEAR_ITEM_H, itemGap: 8, ...legend, } as LegendComponentOption) : undefined; if(yearLegendOpt === undefined && legend !== undefined){ yearLegendOpt = legend; } return { tooltip: tooltip ?? ({ trigger: "axis", axisPointer: { type: "shadow" }, formatter: (params: any) => { const arr = Array.isArray(params) ? params : [params]; const header = arr?.[0]?.axisValueLabel ?? ""; // bar만 const barItems = arr .filter((p: any) => p?.seriesType === "bar") .filter((p: any) => p?.value !== null && p?.value !== undefined); // year -> {total, focus} const map = new Map(); for (const p of barItems) { const sid = String(p.seriesId ?? ""); // total|24, focus|24 const [kind, yStr] = sid.split("|"); const y = Number(yStr); const e = map.get(y) ?? {}; if (kind === "total") e.total = Number(p.value); if (kind === "focus") e.focus = Number(p.value); map.set(y, e); } const lines = [...map.keys()] .sort((a, b) => a - b) .map((y) => { const v = map.get(y)!; const t = v.total ?? 0; const f = v.focus ?? 0; const pct = t > 0 ? ` (${Math.round((f / t) * 100)}%)` : ""; return `${totalName} ${t} 중 ${focusName} ${f}${pct}`; }); return [header, ...lines].join("
"); }, } as TooltipComponentOption), legend: yearLegendOpt ?? undefined, grid: grid ?? defaultGrid, xAxis: xAxis ?? defaultXAxis, yAxis: yAxis ?? defaultYAxis, series: [...yearLegendSeries, ...series], }; }, [ years, data.categories, data.total, data.focus, totalName, focusName, tooltip, grid, xAxis, yAxis, showYearLegend, legend, yearTotalColor, yearFocusColor, barMaxWidth, showFocusLabel, yearLabels, yearSelected, ]); const onEvents = useMemo( () => ({ legendselectchanged: (e: any) => { const name = String(e?.name ?? ""); if (!yearLabels.includes(name)) return; const selected = e?.selected as Record; setYearSelected((prev) => ({ ...prev, [name]: selected?.[name] ?? true, })); }, }), [yearLabels] ); return ; } export default GroupedOverlayBar;