"use client"; /** * V2 출발지/도착지 선택 설정 패널 * 토스식 단계별 UX: 데이터 소스 -> 필드 매핑 -> UI 설정 -> DB 초기값(접힘) */ import React, { useState, useEffect } from "react"; import { Label } from "@/components/ui/label"; import { Input } from "@/components/ui/input"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Switch } from "@/components/ui/switch"; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; import { Settings, ChevronDown } from "lucide-react"; import { cn } from "@/lib/utils"; import { apiClient } from "@/lib/api/client"; interface V2LocationSwapSelectorConfigPanelProps { config: any; onChange: (config: any) => void; tableColumns?: Array<{ columnName: string; columnLabel?: string; dataType?: string }>; screenTableName?: string; } export const V2LocationSwapSelectorConfigPanel: React.FC = ({ config, onChange, tableColumns = [], screenTableName, }) => { const [tables, setTables] = useState>([]); const [columns, setColumns] = useState>([]); const [codeCategories, setCodeCategories] = useState>([]); const [dbSettingsOpen, setDbSettingsOpen] = useState(false); useEffect(() => { const loadTables = async () => { try { const response = await apiClient.get("/table-management/tables"); if (response.data.success && response.data.data) { setTables( response.data.data.map((t: any) => ({ name: t.tableName || t.table_name, label: t.displayName || t.tableLabel || t.table_label || t.tableName || t.table_name, })) ); } } catch (error) { console.error("테이블 목록 로드 실패:", error); } }; loadTables(); }, []); useEffect(() => { const loadColumns = async () => { const tableName = config?.dataSource?.tableName; if (!tableName) { setColumns([]); return; } try { const response = await apiClient.get(`/table-management/tables/${tableName}/columns`); if (response.data.success) { let columnData = response.data.data; if (!Array.isArray(columnData) && columnData?.columns) { columnData = columnData.columns; } if (Array.isArray(columnData)) { setColumns( columnData.map((c: any) => ({ name: c.columnName || c.column_name || c.name, label: c.displayName || c.columnLabel || c.column_label || c.columnName || c.column_name || c.name, })) ); } } } catch (error) { console.error("컬럼 목록 로드 실패:", error); } }; if (config?.dataSource?.type === "table") { loadColumns(); } }, [config?.dataSource?.tableName, config?.dataSource?.type]); useEffect(() => { const loadCodeCategories = async () => { try { const response = await apiClient.get("/code-management/categories"); if (response.data.success && response.data.data) { setCodeCategories( response.data.data.map((c: any) => ({ value: c.category_code || c.categoryCode || c.code, label: c.category_name || c.categoryName || c.name, })) ); } } catch (error: any) { if (error?.response?.status !== 404) { console.error("코드 카테고리 로드 실패:", error); } } }; loadCodeCategories(); }, []); const handleChange = (path: string, value: any) => { const keys = path.split("."); const newConfig = { ...config }; let current: any = newConfig; for (let i = 0; i < keys.length - 1; i++) { if (!current[keys[i]]) { current[keys[i]] = {}; } current[keys[i]] = { ...current[keys[i]] }; current = current[keys[i]]; } current[keys[keys.length - 1]] = value; onChange(newConfig); if (typeof window !== "undefined") { window.dispatchEvent( new CustomEvent("componentConfigChanged", { detail: { config: newConfig }, }) ); } }; const dataSourceType = config?.dataSource?.type || "static"; return (
{/* ─── 1단계: 데이터 소스 ─── */}

데이터 소스

장소 목록을 어디서 가져올지 선택해요

{/* 소스 타입 카드 선택 */}
{[ { value: "static", label: "고정 옵션" }, { value: "table", label: "테이블" }, { value: "code", label: "코드 관리" }, ].map(({ value, label }) => ( ))}
{/* 고정 옵션 설정 */} {dataSourceType === "static" && (

고정된 2개 장소만 사용할 때 설정해요 (예: 포항 / 광양)

{ const options = config?.dataSource?.staticOptions || []; const newOptions = [...options]; newOptions[0] = { ...newOptions[0], value: e.target.value }; handleChange("dataSource.staticOptions", newOptions); }} placeholder="포항" className="h-7 text-xs" />
{ const options = config?.dataSource?.staticOptions || []; const newOptions = [...options]; newOptions[0] = { ...newOptions[0], label: e.target.value }; handleChange("dataSource.staticOptions", newOptions); }} placeholder="포항" className="h-7 text-xs" />
{ const options = config?.dataSource?.staticOptions || []; const newOptions = [...options]; newOptions[1] = { ...newOptions[1], value: e.target.value }; handleChange("dataSource.staticOptions", newOptions); }} placeholder="광양" className="h-7 text-xs" />
{ const options = config?.dataSource?.staticOptions || []; const newOptions = [...options]; newOptions[1] = { ...newOptions[1], label: e.target.value }; handleChange("dataSource.staticOptions", newOptions); }} placeholder="광양" className="h-7 text-xs" />
)} {/* 테이블 설정 */} {dataSourceType === "table" && (
테이블
값 필드
표시 필드
)} {/* 코드 카테고리 설정 */} {dataSourceType === "code" && (
코드 카테고리
)}
{/* ─── 2단계: 필드 매핑 ─── */}

필드 매핑

출발지/도착지 값이 저장될 컬럼을 지정해요 {screenTableName && ( (화면 테이블: {screenTableName}) )}

출발지 저장 컬럼 {tableColumns.length > 0 ? ( ) : ( handleChange("departureField", e.target.value)} className="h-7 w-[140px] text-xs" /> )}
도착지 저장 컬럼 {tableColumns.length > 0 ? ( ) : ( handleChange("destinationField", e.target.value)} className="h-7 w-[140px] text-xs" /> )}
출발지명 컬럼

라벨 저장용 (선택)

{tableColumns.length > 0 ? ( ) : ( handleChange("departureLabelField", e.target.value)} placeholder="departure_name" className="h-7 w-[140px] text-xs" /> )}
도착지명 컬럼

라벨 저장용 (선택)

{tableColumns.length > 0 ? ( ) : ( handleChange("destinationLabelField", e.target.value)} placeholder="destination_name" className="h-7 w-[140px] text-xs" /> )}
{/* ─── 3단계: UI 설정 ─── */}

UI 설정

라벨과 스타일을 설정해요

출발지 라벨 handleChange("departureLabel", e.target.value)} className="h-7 w-[120px] text-xs" />
도착지 라벨 handleChange("destinationLabel", e.target.value)} className="h-7 w-[120px] text-xs" />
스타일

교환 버튼

출발지와 도착지를 바꿀 수 있어요

handleChange("showSwapButton", checked)} />
{/* ─── 4단계: DB 초기값 로드 (Collapsible) ─── */}

DB에서 초기값 로드

새로고침 후에도 DB에 저장된 값을 자동으로 불러와요

handleChange("loadFromDb", checked)} />
{config?.loadFromDb !== false && (
조회 테이블
키 필드

현재 사용자 ID로 조회할 필드

handleChange("dbKeyField", e.target.value)} placeholder="user_id" className="h-7 w-[120px] text-xs" />
)}
); }; V2LocationSwapSelectorConfigPanel.displayName = "V2LocationSwapSelectorConfigPanel"; export default V2LocationSwapSelectorConfigPanel;