import type { DisplayUnit, UnitDim, UnitWeight } from "@/lib/frontend/types"; import { cmToIn, inToCm, kgToLb, lbToKg, toAxelWholeInches, toAxelWholePounds, } from "@/modules/quote/unit-converter"; export function formatCargoInputNumber(value: number): string { if (!Number.isFinite(value)) { return ""; } const rounded = Math.round(value * 100) / 100; return String(rounded); } export function parseCargoInputNumber(raw: string): number | null { const trimmed = raw.trim(); if (!trimmed) { return null; } const value = Number(trimmed); return Number.isFinite(value) ? value : null; } /** 表单内单值重量换算(保持物理量不变) */ export function convertWeightInputValue( value: number, from: UnitWeight, to: UnitWeight, ): number { if (from === to) { return value; } const lb = from === "kg" ? kgToLb(value) : value; return to === "kg" ? lbToKg(lb) : lb; } /** 表单内尺寸换算(保持物理量不变) */ export function convertDimInputValue( value: number, from: UnitDim, to: UnitDim, ): number { if (from === to) { return value; } const inches = from === "cm" ? cmToIn(value) : value; return to === "cm" ? inToCm(inches) : inches; } export function displayUnitToCargoUnits( display: DisplayUnit, ): { weight: UnitWeight; dim: UnitDim } { return display === "metric" ? { weight: "kg", dim: "cm" } : { weight: "lb", dim: "in" }; } /** 展示「询价将按 xxx lb」类提示(界面保留用户输入单位,后端向上取整) */ export function describeWeightEquivalent( value: number, unit: UnitWeight, ): string | null { if (!Number.isFinite(value) || value <= 0) { return null; } const rawLb = unit === "kg" ? kgToLb(value) : value; const queryLb = toAxelWholePounds(rawLb); if (unit === "kg") { return `询价将按 ${queryLb} lb(${formatCargoInputNumber(value)} kg 换算,小数进一)`; } if (queryLb !== rawLb) { return `询价将按 ${queryLb} lb(小数进一)`; } return null; } export function describeDimEquivalent( length: number, width: number, height: number, unit: UnitDim, ): string | null { if ( !Number.isFinite(length) || !Number.isFinite(width) || !Number.isFinite(height) || length <= 0 || width <= 0 || height <= 0 ) { return null; } const toQueryIn = (v: number) => toAxelWholeInches(unit === "cm" ? cmToIn(v) : v); const ql = toQueryIn(length); const qw = toQueryIn(width); const qh = toQueryIn(height); if (unit === "cm") { return `询价将按 ${ql} × ${qw} × ${qh} in(厘米换算,小数进一)`; } const rawL = length; const rawW = width; const rawH = height; if (ql !== rawL || qw !== rawW || qh !== rawH) { return `询价将按 ${ql} × ${qw} × ${qh} in(小数进一)`; } return null; }