productCodeValueTemplate.ts 1.93 KB
import type { LabelElement } from "../types/labelTemplate";
import {
  canonicalElementType,
  isTemplateSectionPersistedType,
  resolvedTypeAddForPersist,
} from "../types/labelTemplate";

/** Template 面板中的条形码 / 二维码(typeAdd 如 template_Barcode、template_QR Code) */
export function isTemplateSectionBarcodeOrQrElement(el: LabelElement): boolean {
  if (!isTemplateSectionPersistedType(el)) return false;
  const t = canonicalElementType(el.type);
  return t === "BARCODE" || t === "QRCODE";
}

/** Label 面板中的条形码 / 二维码(typeAdd 如 label_Barcode、label_QR Code),允许手填 */
export function isLabelSectionBarcodeOrQrElement(el: LabelElement): boolean {
  if (isTemplateSectionPersistedType(el)) return false;
  const t = canonicalElementType(el.type);
  if (t !== "BARCODE" && t !== "QRCODE") return false;
  const typeAdd = resolvedTypeAddForPersist(el).trim().toLowerCase();
  return typeAdd.startsWith("label_");
}

/** 将产品 codeValue 写入 elementId → 字符串,供 templateProductDefaults / 预览合并 */
export function buildTemplateBarcodeQrDefaultsFromCodeValue(
  elements: LabelElement[],
  codeValue: string | null | undefined,
): Record<string, string> {
  const cv = String(codeValue ?? "").trim();
  if (!cv) return {};
  const out: Record<string, string> = {};
  for (const el of elements) {
    if (!isTemplateSectionBarcodeOrQrElement(el)) continue;
    out[el.id] = cv;
  }
  return out;
}

/** 合并 codeValue 到元素 config.data(用于画布预览) */
export function applyProductCodeValueToLabelElements(
  elements: LabelElement[],
  codeValue: string | null | undefined,
): LabelElement[] {
  const cv = String(codeValue ?? "").trim();
  if (!cv) return elements;
  return elements.map((el) => {
    if (!isTemplateSectionBarcodeOrQrElement(el)) return el;
    const cfg = { ...(el.config as Record<string, unknown>) };
    cfg.data = cv;
    return { ...el, config: cfg };
  });
}