"use client"; import { useUiText } from "@suphark/ui/components/shared/ui-text"; import { Table, TableBody, TableCell, TableFooter, TableHead, TableHeader, TableRow, } from "@suphark/ui/components/ui/table"; import { getNumberFormat } from "@suphark/ui/lib/intl-cache"; import { cn } from "@suphark/ui/lib/utils"; import { Fragment, type ReactNode } from "react"; export interface ComparisonColumn { key: string; header: ReactNode; /** บรรทัดเล็กใต้ชื่อ เช่น "ยื่น 28 ต.ค." */ subheader?: ReactNode; } type Num = number | null | undefined; const defaultFormat = (n: number) => getNumberFormat("th-TH", { maximumFractionDigits: 2 }).format(n); const isNum = (v: Num): v is number => typeof v === "number" && Number.isFinite(v); /** คอลัมน์ที่ได้ค่าดีที่สุดของแถว (เสมอกันได้หลายคอลัมน์) — ต้องมีค่าอย่างน้อย 2 ช่องถึงจะเน้น */ function bestKeys(values: Array<[string, Num]>, highlight: "min" | "max" | false) { const nums = values.filter((e): e is [string, number] => isNum(e[1])); if (!highlight || nums.length < 2) return new Set(); const best = highlight === "min" ? Math.min(...nums.map((e) => e[1])) : Math.max(...nums.map((e) => e[1])); return new Set(nums.filter((e) => e[1] === best).map((e) => e[0])); } function diffPercent(value: number, reference: Num) { if (!isNum(reference) || reference === 0) return null; return ((value - reference) / Math.abs(reference)) * 100; } /** * ตารางเทียบ รายการ × ผู้เสนอราคา/รุ่น: คอลัมน์แรกติดซ้าย, หัวกลุ่ม (`groupBy`), เน้นค่าดีที่สุดต่อแถว * (`highlight="min"` ราคาต่ำสุด), % ต่างจากคอลัมน์อ้างอิง (ราคากลาง), แถวรวมท้าย · จอ < md เป็นรายการทีละแถว * เรียงจากดีไปแย่ — ตารางแสดงผลอย่างเดียว (sort/filter ใช้ DataTable) * * r.id} rowLabel={(r) => r.name} groupBy={(r) => r.category} * columns={bidders.map((b) => ({ key: b.id, header: b.name }))} * value={(row, col) => row.prices[col.key]} * reference={{ header: "ราคากลาง", value: (r) => r.budget }} total /> * * ช่องที่ไม่มีค่า (null/undefined) แสดง "—" และไม่นับในการเน้น · แถวรวม = ผลรวมเฉพาะช่องที่มีค่า */ export function ComparisonMatrix({ rows, rowKey, rowLabel, rowHint, groupBy, columns, value, reference, highlight = "min", showDiff = true, total = false, format = defaultFormat, className, "aria-label": ariaLabel, }: { rows: ReadonlyArray; rowKey: (row: R) => string; rowLabel: (row: R) => ReactNode; /** บรรทัดเล็กใต้ชื่อรายการ เช่น หน่วย/จำนวน */ rowHint?: (row: R) => ReactNode; /** ชื่อหมวดของแถว — แถวที่ติดกันหมวดเดียวกันอยู่ใต้หัวหมวดเดียว (ส่งแถวที่เรียงตามหมวดมาแล้ว) */ groupBy?: (row: R) => string | null | undefined; columns: ReadonlyArray; value: (row: R, column: ComparisonColumn) => Num; /** คอลัมน์อ้างอิงหน้าสุด (ราคากลาง/งบประมาณ) — ใช้คำนวณ % ต่าง */ reference?: { header: ReactNode; value: (row: R) => Num }; /** เน้นค่าน้อยสุด (ราคา) หรือมากสุด (คะแนน) ต่อแถว · false = ไม่เน้น */ highlight?: "min" | "max" | false; /** แสดง % เทียบคอลัมน์อ้างอิง (ต้องมี `reference`) */ showDiff?: boolean; /** แถวรวมท้ายตาราง — `{ label }` เปลี่ยนชื่อแถว */ total?: boolean | { label?: ReactNode }; format?: (n: number) => string; className?: string; "aria-label"?: string; }) { const text = useUiText().comparison; const bestLabel = highlight === "max" ? (text?.highest ?? "สูงสุด") : (text?.lowest ?? "ต่ำสุด"); const totalLabel = (typeof total === "object" && total.label) || (text?.total ?? "รวมทั้งสิ้น"); const withDiff = showDiff && reference !== undefined; // ทิศที่ "แย่": ราคาสูงกว่าอ้างอิงเป็นสีแดงเมื่อหาค่าต่ำสุด และกลับกันเมื่อหาค่าสูงสุด const worse = (pct: number) => (highlight === "max" ? pct < 0 : pct > 0); const sum = (pick: (row: R) => Num) => { let acc = 0; let any = false; for (const row of rows) { const v = pick(row); if (isNum(v)) { acc += v; any = true; } } return any ? acc : null; }; // ผลรวมของคอลัมน์ที่เสนอไม่ครบทุกแถวเทียบกับคอลัมน์อื่นไม่ได้ → ไม่เน้น ไม่คิด % และมีป้าย "ไม่ครบ" const totals = total ? { reference: reference ? sum(reference.value) : null, cells: columns.map((c) => [c.key, sum((r) => value(r, c))] as [string, Num]), incomplete: new Set( columns.filter((c) => rows.some((r) => !isNum(value(r, c)))).map((c) => c.key), ), } : null; const incompleteLabel = text?.incomplete ?? "เสนอไม่ครบ"; const groups: Array<{ name: string | null; rows: R[] }> = []; for (const row of rows) { const name = groupBy?.(row) ?? null; const lastGroup = groups.at(-1); if (lastGroup && lastGroup.name === name) lastGroup.rows.push(row); else groups.push({ name, rows: [row] }); } const cell = (v: Num, ref: Num, best: boolean) => { if (!isNum(v)) return —; const pct = withDiff ? diffPercent(v, ref) : null; return ( <> {format(v)} {best && ({bestLabel})} {pct !== null && ( {formatPct(pct)} )} ); }; const span = columns.length + 1 + (reference ? 1 : 0); const stickyCell = "sticky left-0 z-1 bg-card"; return (
{text?.item ?? "รายการ"} {reference && {reference.header}} {columns.map((c) => ( {c.header} {c.subheader && ( {c.subheader} )} ))} {groups.map((group, gi) => ( // biome-ignore lint/suspicious/noArrayIndexKey: หมวดชื่อซ้ำได้ถ้าแถวไม่ได้เรียงติดกัน {group.name !== null && ( {group.name} )} {group.rows.map((row) => { const ref = reference?.value(row); const values = columns.map((c) => [c.key, value(row, c)] as [string, Num]); const best = bestKeys(values, highlight); return ( {/* หัวแถว =
— โปรแกรมอ่านจออ่านชื่อรายการคู่กับตัวเลขแต่ละช่อง (เดิม ) */} {rowLabel(row)} {rowHint && ( {rowHint(row)} )} {reference && ( {isNum(ref) ? format(ref) : "—"} )} {values.map(([key, v]) => ( {cell(v, ref, best.has(key))} ))} ); })} ))} {totals && ( {totalLabel} {reference && ( {isNum(totals.reference) ? format(totals.reference) : "—"} )} {(() => { const best = bestKeys( totals.cells.map(([key, v]) => [key, totals.incomplete.has(key) ? null : v]), highlight, ); return totals.cells.map(([key, v]) => ( {totals.incomplete.has(key) ? ( <> {isNum(v) ? format(v) : "—"} {incompleteLabel} ) : ( cell(v, totals.reference, best.has(key)) )} )); })()} )}
{/* จอแคบ: ทีละรายการ เรียงจากดีไปแย่ */}
    {rows.map((row) => ( ({ column: c, value: value(row, c) }))} highlight={highlight} bestLabel={bestLabel} format={format} worse={withDiff ? worse : null} /> ))} {totals && ( {totalLabel}} referenceHeader={reference?.header} reference={totals.reference} values={columns.map((c, i) => ({ column: c, value: totals.cells[i]?.[1], note: totals.incomplete.has(c.key) ? incompleteLabel : undefined, }))} highlight={highlight} bestLabel={bestLabel} format={format} worse={withDiff ? worse : null} /> )}
); } function formatPct(pct: number) { const rounded = Math.round(pct * 10) / 10; if (rounded === 0) return "0%"; return `${rounded > 0 ? "+" : "−"}${Math.abs(rounded).toFixed(1)}%`; } function MobileItem({ label, hint, referenceHeader, reference, values, highlight, bestLabel, format, worse, }: { label: ReactNode; hint?: ReactNode; referenceHeader?: ReactNode; reference: Num; /** `note` = ค่านี้เทียบไม่ได้ (เช่น ผลรวมที่เสนอไม่ครบ): ไม่เน้น ไม่คิด % แสดงป้ายแทน */ values: Array<{ column: ComparisonColumn; value: Num; note?: string }>; highlight: "min" | "max" | false; bestLabel: string; format: (n: number) => string; worse: ((pct: number) => boolean) | null; }) { const best = bestKeys( values.map((v) => [v.column.key, v.note ? null : v.value]), highlight, ); const sorted = [...values].sort((a, b) => { if (!isNum(a.value)) return 1; if (!isNum(b.value)) return -1; return highlight === "max" ? b.value - a.value : a.value - b.value; }); return (
  • {label} {hint && {hint}} {referenceHeader && isNum(reference) && ( {referenceHeader} {format(reference)} )}
      {sorted.map(({ column, value: v, note }) => { const isBest = best.has(column.key); const pct = worse && isNum(v) && !note ? diffPercent(v, reference) : null; return (
    • {column.header} {isBest && ` · ${bestLabel}`} {isNum(v) ? format(v) : "—"} {note && · {note}} {pct !== null && pct !== 0 && worse?.(pct) && ( · {formatPct(pct)} )}
    • ); })}
  • ); }