index.tsx 36.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Button } from '../../ui/button';
import { ArrowLeft, Save, Download } from 'lucide-react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '../../ui/dialog';
import { Input } from '../../ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '../../ui/select';
import type { ElementLibraryCategory, LabelTemplate, LabelElement, PrintOrientation } from '../../../types/labelTemplate';
import {
  buildLabelTemplateScopePayload,
  allocateElementName,
  canonicalElementType,
  composeElementTypeForPersist,
  composeLibraryCategoryForPersist,
  createDefaultTemplate,
  createDefaultElement,
  applyPaletteLabelDefaultText,
  labelElementsToApiPayload,
  normalizePrintOrientation,
  PRESET_LABEL_SIZES,
  resolvedLibraryCategoryForPersist,
  resolvedTypeAddForPersist,
  resolvedValueSourceTypeForSave,
  stripLabelConfigPrefixes,
  valueSourceTypeForLibraryCategory,
} from '../../../types/labelTemplate';
import { ElementsPanel } from './ElementsPanel';
import { LabelCanvas, LabelPreviewOnly, clampLabelElementBox, mergeLabelElementLivePatch, mergeTemplateElementsLivePatch, type LabelElementLivePatch } from './LabelCanvas';
import type { PreviewRulerDisplayUnit } from '@/utils/previewRulerUnits';
import { PropertiesPanel } from './PropertiesPanel';
import { createLabelTemplate, getLabelTemplate, getLabelTemplates, updateLabelTemplate } from '../../../services/labelTemplateService';
import { sanitizeNutritionElementsForTemplateEditor } from '../../../lib/nutritionManualEntry';
import { getLocations } from '../../../services/locationService';
import { getGroups } from '../../../services/groupService';
import { getPartners } from '../../../services/partnerService';
import { skipCountForPage } from '../../../lib/paginationQuery';
import {
  hydrateLabelTemplateScopeFromDto,
  locationsScopedForTemplateScope,
  regionOptionsForPartners,
} from '../../../lib/categoryScopeForm';
import { CategoryScopeFields } from '../../shared/category-scope-fields';
import { useCategoryScopeAuth } from '../../../hooks/useCategoryScopeAuth';
import {
  TemplateFieldGroup,
  templateFieldInputClass,
  templateFieldSelectTriggerClass,
  templateUnitShortLabel,
} from './template-editor-field-group';
import type { LocationDto } from '../../../types/location';
import type { GroupListItem } from '../../../types/group';
import type { PartnerListItem } from '../../../types/partner';
import { toast } from 'sonner';

const MIN_SCALE = 0.5;
const MAX_SCALE = 2;
const SCALE_STEP = 0.25;
const DEFAULT_SCALE = 1.0;

function buildCopiedTemplateId(sourceId: string): string {
  const seed = Math.random().toString(36).slice(2, 8);
  return `tpl_${seed}_${Date.now().toString(36)}`;
}

function cloneStarterTemplate(source: LabelTemplate): LabelTemplate {
  return {
    ...source,
    id: buildCopiedTemplateId(source.id),
    name: `${(source.name || "Unnamed template").trim()} Copy`,
    elements: source.elements.map((el) => ({
      ...el,
      config: { ...(el.config ?? {}) },
    })),
  };
}

interface LabelTemplateEditorProps {
  /** null = 新建,string = 编辑该 id */
  templateId: string | null;
  initialTemplate: LabelTemplate | null;
  onClose: () => void;
  onSaved: () => void;
}

export function LabelTemplateEditor({
  templateId,
  initialTemplate,
  onClose,
  onSaved,
}: LabelTemplateEditorProps) {
  const scopeAuth = useCategoryScopeAuth();
  const [template, setTemplate] = useState<LabelTemplate>(() => {
    if (initialTemplate) {
      return {
        ...initialTemplate,
        elements: sanitizeNutritionElementsForTemplateEditor(initialTemplate.elements),
      };
    }
    const next = createDefaultTemplate(templateId ?? undefined);
    return {
      ...next,
      id: buildCopiedTemplateId(next.id || "template"),
    };
  });
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [liveElementPatch, setLiveElementPatch] = useState<LabelElementLivePatch | null>(null);
  const liveElementPatchRef = useRef<LabelElementLivePatch | null>(null);
  liveElementPatchRef.current = liveElementPatch;
  const [scale, setScale] = useState(DEFAULT_SCALE);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewRulerUnit, setPreviewRulerUnit] = useState<PreviewRulerDisplayUnit>('cm');
  const [starterOptions, setStarterOptions] = useState<Array<{ code: string; name: string }>>([]);
  const [selectedStarterCode, setSelectedStarterCode] = useState<string>('');
  const [loadingStarter, setLoadingStarter] = useState(false);

  const [locationCatalog, setLocationCatalog] = useState<LocationDto[]>([]);
  const [filterGroups, setFilterGroups] = useState<GroupListItem[]>([]);
  const [filterPartners, setFilterPartners] = useState<PartnerListItem[]>([]);
  const [scopeCatalogReady, setScopeCatalogReady] = useState(false);
  const [scopePartnerIds, setScopePartnerIds] = useState<string[]>([]);
  const [scopeRegionIds, setScopeRegionIds] = useState<string[]>([]);
  const [scopeLocationIds, setScopeLocationIds] = useState<string[]>([]);
  const scopeHydrateKeyRef = useRef('');

  const selectedElement = useMemo(() => {
    const el = template.elements.find((item) => item.id === selectedId) ?? null;
    if (!el) return null;
    return mergeLabelElementLivePatch(el, liveElementPatch);
  }, [template.elements, selectedId, liveElementPatch]);

  const previewTemplate = useMemo(
    () => ({
      ...template,
      elements: mergeTemplateElementsLivePatch(template.elements, liveElementPatch),
    }),
    [template, liveElementPatch],
  );

  const printOrientation = template.printOrientation ?? 'vertical';

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const out: LocationDto[] = [];
        let locPage = 1;
        const locSize = 500;
        for (;;) {
          const res = await getLocations({
            skipCount: skipCountForPage(locPage),
            maxResultCount: locSize,
          });
          out.push(...(res.items ?? []));
          if (!res.items || res.items.length < locSize) break;
          locPage += 1;
          if (locPage > 200) break;
        }
        const [grpRes, partnerRes] = await Promise.all([
          getGroups({ skipCount: 1, maxResultCount: 500 }),
          getPartners({ skipCount: 1, maxResultCount: 500, state: true }),
        ]);
        if (cancelled) return;
        setLocationCatalog(out);
        setFilterGroups(grpRes.items ?? []);
        setFilterPartners(partnerRes.items ?? []);
        setScopeCatalogReady(true);
      } catch {
        if (!cancelled) {
          setLocationCatalog([]);
          setFilterGroups([]);
          setFilterPartners([]);
          setScopeCatalogReady(false);
        }
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  useEffect(() => {
    if (!scopeCatalogReady) return;
    const partnerKey = (template.partnerIds ?? []).join(',');
    const regionKey = (template.regionIds ?? []).join(',');
    const locKey = (template.appliedLocationIds ?? []).join(',');
    const key = [
      template.id,
      template.appliedPartnerType ?? '',
      template.appliedRegionType ?? '',
      template.appliedLocation,
      partnerKey,
      regionKey,
      locKey,
    ].join(':');
    if (scopeHydrateKeyRef.current === key) return;
    scopeHydrateKeyRef.current = key;

    const scope = hydrateLabelTemplateScopeFromDto(
      {
        appliedPartnerType: template.appliedPartnerType,
        appliedRegionType: template.appliedRegionType,
        appliedLocation: template.appliedLocation,
        partnerIds: template.partnerIds,
        companyIds: template.companyIds,
        regionIds: template.regionIds,
        groupIds: template.groupIds,
        locationIds: template.appliedLocationIds,
        appliedLocationIds: template.appliedLocationIds,
      },
      locationCatalog,
      filterPartners,
      filterGroups,
    );
    setScopePartnerIds(scope.partnerIds);
    setScopeRegionIds(scope.regionIds);
    setScopeLocationIds(scope.locationIds);
  }, [
    scopeCatalogReady,
    template.id,
    template.appliedPartnerType,
    template.appliedRegionType,
    template.appliedLocation,
    template.partnerIds,
    template.companyIds,
    template.regionIds,
    template.groupIds,
    template.appliedLocationIds,
    locationCatalog,
    filterPartners,
    filterGroups,
  ]);

  useEffect(() => {
    if (templateId) return;
    let cancelled = false;
    (async () => {
      try {
        const res = await getLabelTemplates({ skipCount: 1, maxResultCount: 200 });
        if (cancelled) return;
        const options = (res.items ?? [])
          .map((x) => {
            const code = (x.templateCode ?? x.id ?? '').trim();
            const name = (x.templateName ?? x.name ?? code).trim();
            return code ? { code, name } : null;
          })
          .filter((x): x is { code: string; name: string } => !!x);
        setStarterOptions(options);
        if (!selectedStarterCode && options.length > 0) {
          setSelectedStarterCode(options[0].code);
        }
      } catch {
        if (!cancelled) setStarterOptions([]);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [templateId, selectedStarterCode]);

  useEffect(() => {
    if (templateId || !selectedStarterCode) return;
    let cancelled = false;
    (async () => {
      setLoadingStarter(true);
      try {
        const apiTemplate = await getLabelTemplate(selectedStarterCode);
        if (cancelled) return;
        const copied = cloneStarterTemplate({
          id: apiTemplate.id,
          name: (apiTemplate.name ?? apiTemplate.templateName ?? '').trim() || 'Unnamed template',
          labelType: (apiTemplate.labelType as any) ?? 'PRICE',
          unit: (apiTemplate.unit as any) ?? 'cm',
          width: Number(apiTemplate.width ?? 6),
          height: Number(apiTemplate.height ?? 4),
          appliedLocation: apiTemplate.appliedLocation === 'SPECIFIED' ? 'SPECIFIED' : 'ALL',
          appliedLocationIds: [...(apiTemplate.appliedLocationIds ?? apiTemplate.locationIds ?? [])],
          appliedPartnerType: apiTemplate.appliedPartnerType as any,
          appliedRegionType: apiTemplate.appliedRegionType as any,
          partnerIds: [...(apiTemplate.partnerIds ?? apiTemplate.companyIds ?? [])],
          companyIds: [...(apiTemplate.companyIds ?? apiTemplate.partnerIds ?? [])],
          regionIds: [
            ...new Set(
              [...(apiTemplate.regionIds ?? []), ...(apiTemplate.groupIds ?? [])]
                .map((x) => String(x).trim())
                .filter(Boolean),
            ),
          ],
          groupIds: [
            ...new Set(
              [...(apiTemplate.regionIds ?? []), ...(apiTemplate.groupIds ?? [])]
                .map((x) => String(x).trim())
                .filter(Boolean),
            ),
          ],
          showRuler: apiTemplate.showRuler ?? true,
          showGrid: apiTemplate.showGrid ?? true,
          border: apiTemplate.border ?? 'none',
          printOrientation: normalizePrintOrientation(
            apiTemplate.printOrientation ?? (apiTemplate as Record<string, unknown>).PrintOrientation,
          ),
          elements: sanitizeNutritionElementsForTemplateEditor(
            (apiTemplate.elements ?? []).map((raw, idx) => {
              const el = raw as LabelElement;
              const en = (el.elementName ?? '').trim();
              return { ...el, elementName: en || `element${idx + 1}` };
            }),
          ),
        });
        setTemplate(copied);
        setLiveElementPatch(null);
        setSelectedId(null);
      } catch (e: any) {
        if (cancelled) return;
        toast.error("Failed to copy starter template.", {
          description: e?.message ? String(e.message) : "Please try again.",
        });
      } finally {
        if (!cancelled) setLoadingStarter(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [templateId, selectedStarterCode]);

  /** 纸张尺寸或单位变化时,将已有控件限制在安全区内 */
  useEffect(() => {
    setTemplate((prev) => {
      const unitToPx = (value: number, unit: "cm" | "inch"): number =>
        unit === "cm" ? value * 37.8 : value * 96;
      const baseW = unitToPx(prev.width, prev.unit);
      const baseH = unitToPx(prev.height, prev.unit);
      let changed = false;
      const elements = prev.elements.map((el) => {
        const c = clampLabelElementBox(el.x, el.y, el.width, el.height, baseW, baseH);
        if (el.x !== c.x || el.y !== c.y || el.width !== c.w || el.height !== c.h) {
          changed = true;
          return { ...el, x: c.x, y: c.y, width: c.w, height: c.h };
        }
        return el;
      });
      if (!changed) return prev;
      return { ...prev, elements };
    });
  }, [template.width, template.height, template.unit, template.id]);

  const templateBorderValue = template.border ?? 'none';

  /** 配置区单行 flex */
  const configRowClass = "flex w-full min-w-0 flex-wrap items-center gap-2";

  const updateElement = useCallback((id: string, patch: Partial<LabelElement>) => {
    setTemplate((prev) => {
      const unitToPx = (value: number, unit: "cm" | "inch"): number =>
        unit === "cm" ? value * 37.8 : value * 96;
      const baseW = unitToPx(prev.width, prev.unit);
      const baseH = unitToPx(prev.height, prev.unit);
      const orientation = prev.printOrientation ?? 'vertical';
      return {
        ...prev,
        elements: prev.elements.map((el) => {
          if (el.id !== id) return el;
          const merged = { ...el, ...patch };
          const geomTouched =
            patch.x !== undefined ||
            patch.y !== undefined ||
            patch.width !== undefined ||
            patch.height !== undefined;
          if (!geomTouched) return merged;
          const c = clampLabelElementBox(
            merged.x,
            merged.y,
            merged.width,
            merged.height,
            baseW,
            baseH,
            undefined,
            orientation,
          );
          return { ...merged, x: c.x, y: c.y, width: c.w, height: c.h };
        }),
      };
    });
  }, []);

  const flushLiveElementPatch = useCallback(() => {
    const patch = liveElementPatchRef.current;
    if (!patch?.id) return;
    const { id, x, y, width, height } = patch;
    const geom: Partial<LabelElement> = {};
    if (x !== undefined) geom.x = x;
    if (y !== undefined) geom.y = y;
    if (width !== undefined) geom.width = width;
    if (height !== undefined) geom.height = height;
    if (Object.keys(geom).length > 0) {
      updateElement(id, geom);
    }
    setLiveElementPatch(null);
  }, [updateElement]);

  const handleSelectElement = useCallback((id: string | null) => {
    flushLiveElementPatch();
    setSelectedId(id);
  }, [flushLiveElementPatch]);

  const addElement = useCallback((
    type: Parameters<typeof createDefaultElement>[0],
    configOverride: Partial<Record<string, unknown>> | undefined,
    libraryCategory: ElementLibraryCategory,
    paletteItemLabel: string,
  ) => {
    let addedId = "";
    setTemplate((prev) => {
      const unitToPx = (value: number, unit: "cm" | "inch"): number =>
        unit === "cm" ? value * 37.8 : value * 96;

      const canvasWidthPx = unitToPx(prev.width, prev.unit);
      const canvasHeightPx = unitToPx(prev.height, prev.unit);

      let el = createDefaultElement(type, 0, 0);
      const GRID_SIZE = 8;
      const snapToGrid = (value: number): number =>
        Math.round(value / GRID_SIZE) * GRID_SIZE;

      let centerX = (canvasWidthPx - el.width) / 2;
      let centerY = (canvasHeightPx - el.height) / 2;

      const checkOverlap = (x: number, y: number, width: number, height: number): boolean =>
        prev.elements.some((o) => {
          const elRight = o.x + o.width;
          const elBottom = o.y + o.height;
          const newRight = x + width;
          const newBottom = y + height;
          return !(x >= elRight || newRight <= o.x || y >= elBottom || newBottom <= o.y);
        });

      if (checkOverlap(centerX, centerY, el.width, el.height)) {
        const offset = GRID_SIZE * 2;
        let found = false;
        for (let tryY = centerY; tryY < canvasHeightPx - el.height && !found; tryY += offset) {
          for (let tryX = centerX; tryX < canvasWidthPx - el.width && !found; tryX += offset) {
            if (!checkOverlap(tryX, tryY, el.width, el.height)) {
              centerX = tryX;
              centerY = tryY;
              found = true;
            }
          }
        }
        if (!found) {
          for (let tryY = centerY; tryY >= 0 && !found; tryY -= offset) {
            for (let tryX = centerX; tryX >= 0 && !found; tryX -= offset) {
              if (!checkOverlap(tryX, tryY, el.width, el.height)) {
                centerX = tryX;
                centerY = tryY;
                found = true;
              }
            }
          }
        }
      }

      el = {
        ...el,
        x: Math.max(0, snapToGrid(centerX)),
        y: Math.max(0, snapToGrid(centerY)),
      };
      if (paletteItemLabel.trim().toLowerCase() === "label id") {
        const bottomY = Math.max(0, canvasHeightPx - el.height - GRID_SIZE);
        el = { ...el, y: snapToGrid(bottomY) };
      }
      const box = clampLabelElementBox(el.x, el.y, el.width, el.height, canvasWidthPx, canvasHeightPx);
      el = { ...el, x: box.x, y: box.y, width: box.w, height: box.h };
      if (configOverride && Object.keys(configOverride).length > 0) {
        el.config = { ...el.config, ...configOverride };
      }
      el.config = applyPaletteLabelDefaultText(
        type,
        el.config as Record<string, unknown>,
        paletteItemLabel,
        configOverride,
      );
      const elementName = allocateElementName(paletteItemLabel, prev.elements);
      const vst = valueSourceTypeForLibraryCategory(libraryCategory);
      el = {
        ...el,
        type: el.type,
        typeAdd: composeElementTypeForPersist(libraryCategory, paletteItemLabel),
        libraryCategory: composeLibraryCategoryForPersist(libraryCategory, paletteItemLabel),
        valueSourceType: vst,
        elementName,
      };
      addedId = el.id;
      return { ...prev, elements: [...prev.elements, el] };
    });
    handleSelectElement(addedId);
  }, [template.width, template.height, template.unit, handleSelectElement]);

  const deleteElement = useCallback((id: string) => {
    setTemplate((prev) => ({
      ...prev,
      elements: prev.elements.filter((el) => el.id !== id),
    }));
    handleSelectElement(null);
  }, [handleSelectElement]);

  const handleTemplateChange = useCallback((patch: Partial<LabelTemplate>) => {
    setTemplate((prev) => ({ ...prev, ...patch }));
  }, []);

  const handlePrintOrientationChange = useCallback((orientation: PrintOrientation) => {
    flushLiveElementPatch();
    handleTemplateChange({ printOrientation: orientation });
  }, [flushLiveElementPatch, handleTemplateChange]);

  const handleSave = useCallback(async () => {
    try {
      const code = (template.id ?? "").trim();
      if (!code) {
        toast.error("Template code is required.", {
          description: "Please enter a template code (e.g. TPL_TEST_001).",
        });
        return;
      }
      const emptyName = template.elements.find(
        (el) => !(el.elementName ?? "").trim(),
      );
      if (emptyName) {
        toast.error("Component name required.", {
          description: "Each element must have a non-empty element name.",
        });
        return;
      }

      const optionsWithoutDictionary = template.elements.find((el) => {
        if (el.type !== "TEXT_STATIC") return false;
        const cfg = el.config as Record<string, unknown>;
        if (String(cfg?.inputType ?? "").toLowerCase() !== "options") return false;
        const mid = String(cfg?.multipleOptionId ?? cfg?.MultipleOptionId ?? "").trim();
        return !mid;
      });
      if (optionsWithoutDictionary) {
        toast.error("Option dictionary required.", {
          description:
            "Each Multiple Options element must have an Option dictionary selected in the properties panel.",
        });
        return;
      }

      const effectivePartnerIds = scopeAuth.requireCompanySelection
        ? scopePartnerIds
        : [scopeAuth.fixedPartnerId.trim()].filter(Boolean);
      const availablePartnerIds = scopeAuth.requireCompanySelection
        ? filterPartners.map((p) => p.id).filter(Boolean)
        : effectivePartnerIds;
      const availableRegionIds = regionOptionsForPartners(
        filterGroups,
        effectivePartnerIds.length > 0 ? effectivePartnerIds : availablePartnerIds,
      ).map((o) => o.value);
      const scopedLocations = locationsScopedForTemplateScope(
        locationCatalog,
        filterPartners,
        filterGroups,
        effectivePartnerIds,
        scopeRegionIds,
      );
      const availableLocationIds = scopedLocations.map((l) => l.id);

      const scopePayload = buildLabelTemplateScopePayload({
        selectedPartnerIds: effectivePartnerIds,
        selectedRegionIds: scopeRegionIds,
        selectedLocationIds: scopeLocationIds,
        availablePartnerIds,
        availableRegionIds,
        availableLocationIds,
      });
      if (!scopePayload.ok) {
        toast.error("Validation failed", { description: scopePayload.message });
        return;
      }

      const apiInput = {
        id: code,
        name: template.name,
        labelType: template.labelType,
        unit: template.unit,
        width: template.width,
        height: template.height,
        showRuler: true,
        showGrid: template.showGrid ?? true,
        border: template.border ?? 'none',
        printOrientation: template.printOrientation ?? 'vertical',
        state: true,
        elements: labelElementsToApiPayload(
          sanitizeNutritionElementsForTemplateEditor(template.elements),
        ),
        ...scopePayload.body,
      };

      if (templateId) {
        // 编辑模式:使用 TemplateCode 作为 id
        await updateLabelTemplate(code, apiInput);
        toast.success("Template updated.", {
          description: "The template has been updated successfully.",
        });
      } else {
        // 新建模式
        await createLabelTemplate(apiInput);
        toast.success("Template created.", {
          description: "The template has been created successfully.",
        });
      }
      onSaved();
      onClose();
    } catch (e: any) {
      toast.error("Failed to save template.", {
        description: e?.message ? String(e.message) : "Please try again.",
      });
    }
  }, [
    template,
    templateId,
    onSaved,
    onClose,
    locationCatalog,
    filterPartners,
    filterGroups,
    scopeAuth.requireCompanySelection,
    scopeAuth.fixedPartnerId,
    scopePartnerIds,
    scopeRegionIds,
    scopeLocationIds,
  ]);

  const handleExport = useCallback(() => {
    const payload: LabelTemplate = {
      ...template,
      elements: template.elements.map((el) => ({
        ...el,
        type: canonicalElementType(el.type),
        typeAdd: resolvedTypeAddForPersist(el),
        elementName: (el.elementName ?? "").trim(),
        valueSourceType: resolvedValueSourceTypeForSave(el),
        libraryCategory: resolvedLibraryCategoryForPersist(el),
        config: stripLabelConfigPrefixes((el.config ?? {}) as Record<string, unknown>),
      })),
    };
    const blob = new Blob([JSON.stringify(payload, null, 2)], {
      type: 'application/json',
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `label-template-${template.id}.json`;
    a.click();
    URL.revokeObjectURL(url);
  }, [template]);

  return (
    <div
      className="flex flex-col overflow-hidden"
      style={{
        flex: "1 1 0%",
        minHeight: 0,
        display: "flex",
        flexDirection: "column",
        overflow: "hidden",
      }}
    >
      {/* 顶栏:仅导航与保存 */}
      <div className="flex shrink-0 items-center gap-2 border-b border-gray-200 bg-white px-4 py-2">
        <Button
          size="sm"
          className="h-8 shrink-0 bg-blue-600 px-3 text-xs text-white hover:bg-blue-700"
          onClick={onClose}
        >
          <ArrowLeft className="mr-1 h-3.5 w-3.5" />
          Back
        </Button>
        <span className="min-w-0 flex-1 truncate text-sm font-medium text-gray-700">{template.name}</span>
        <Button size="sm" variant="outline" className="h-8 shrink-0 text-xs" onClick={handleExport}>
          <Download className="mr-1 h-3.5 w-3.5" />
          Export JSON
        </Button>
        <Button
          size="sm"
          className="h-8 shrink-0 bg-blue-600 px-3 text-xs text-white hover:bg-blue-700"
          onClick={handleSave}
        >
          <Save className="mr-1 h-3.5 w-3.5" />
          Save
        </Button>
      </div>

      {/* 模板配置区:统一 input-group 样式 */}
      <div className="shrink-0 border-b border-[#cfd9ea] bg-[#dde7f5] px-4 py-2">
        <div className="rounded-lg border border-[#c2d1e8] bg-[#e4ecf8] p-2">
          <div className="flex flex-col gap-2">
            <div className={configRowClass}>
              <TemplateFieldGroup label="Name:" className="min-w-[10rem] flex-[1_1_12rem] max-w-sm">
                <Input
                  value={template.name}
                  onChange={(e) => handleTemplateChange({ name: e.target.value })}
                  className={templateFieldInputClass}
                />
              </TemplateFieldGroup>

              <TemplateFieldGroup label="Unit:" className="w-[6.75rem] shrink-0">
                <Select
                  value={template.unit}
                  onValueChange={(v: "cm" | "inch") => handleTemplateChange({ unit: v, showRuler: true })}
                >
                  <SelectTrigger className={templateFieldSelectTriggerClass}>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="inch" className="text-xs">
                      Inch
                    </SelectItem>
                    <SelectItem value="cm" className="text-xs">
                      cm
                    </SelectItem>
                  </SelectContent>
                </Select>
              </TemplateFieldGroup>

              <TemplateFieldGroup
                label="W:"
                suffix={templateUnitShortLabel(template.unit)}
                className="w-[5.25rem] shrink-0"
              >
                <Input
                  type="number"
                  value={template.width}
                  onChange={(e) =>
                    handleTemplateChange({ width: Math.max(0.1, Number(e.target.value) || 0), showRuler: true })
                  }
                  className={`${templateFieldInputClass} px-1 text-center`}
                />
              </TemplateFieldGroup>

              <TemplateFieldGroup
                label="H:"
                suffix={templateUnitShortLabel(template.unit)}
                className="w-[5.25rem] shrink-0"
              >
                <Input
                  type="number"
                  value={template.height}
                  onChange={(e) =>
                    handleTemplateChange({ height: Math.max(0.1, Number(e.target.value) || 0), showRuler: true })
                  }
                  className={`${templateFieldInputClass} px-1 text-center`}
                />
              </TemplateFieldGroup>

              <TemplateFieldGroup label="Size Preset:" className="w-[8.5rem] shrink-0">
                <Select
                  value={(() => {
                    const i = PRESET_LABEL_SIZES.findIndex(
                      (p) =>
                        p.width === template.width && p.height === template.height && p.unit === template.unit,
                    );
                    return i >= 0 ? String(i) : "custom";
                  })()}
                  onValueChange={(v: string) => {
                    if (v === "custom") return;
                    const p = PRESET_LABEL_SIZES[Number(v)];
                    if (p) handleTemplateChange({ width: p.width, height: p.height, unit: p.unit, showRuler: true });
                  }}
                >
                  <SelectTrigger className={templateFieldSelectTriggerClass}>
                    <SelectValue placeholder="Canvas size" />
                  </SelectTrigger>
                  <SelectContent>
                    {PRESET_LABEL_SIZES.map((p, i) => (
                      <SelectItem key={i} value={String(i)} className="text-xs">
                        {p.name}
                      </SelectItem>
                    ))}
                    <SelectItem value="custom" className="text-xs text-gray-500">
                      Custom
                    </SelectItem>
                  </SelectContent>
                </Select>
              </TemplateFieldGroup>

              <TemplateFieldGroup label="Starter Template:" className="min-w-[9rem] flex-[1_1_10rem]">
                {!templateId ? (
                  <Select value={selectedStarterCode} onValueChange={setSelectedStarterCode}>
                    <SelectTrigger className={templateFieldSelectTriggerClass}>
                      <SelectValue placeholder="Select starter template" />
                    </SelectTrigger>
                    <SelectContent>
                      {starterOptions.map((op) => (
                        <SelectItem key={op.code} value={op.code} className="text-xs">
                          {op.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                ) : (
                  <Input value="Current template" disabled className={templateFieldInputClass} />
                )}
              </TemplateFieldGroup>

              <TemplateFieldGroup label="Border:" className="w-[7.5rem] shrink-0">
                <Select
                  value={templateBorderValue}
                  onValueChange={(v: "none" | "line" | "dotted") => handleTemplateChange({ border: v })}
                >
                  <SelectTrigger className={templateFieldSelectTriggerClass}>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none" className="text-xs">
                      none
                    </SelectItem>
                    <SelectItem value="line" className="text-xs">
                      line
                    </SelectItem>
                    <SelectItem value="dotted" className="text-xs">
                      dotted
                    </SelectItem>
                  </SelectContent>
                </Select>
              </TemplateFieldGroup>
            </div>

            <div className={`${configRowClass} flex-nowrap`}>
              <TemplateFieldGroup label="Rotation:" className="w-[8.5rem] shrink-0">
                <Select
                  value={printOrientation}
                  onValueChange={(v: PrintOrientation) => handlePrintOrientationChange(v)}
                >
                  <SelectTrigger className={templateFieldSelectTriggerClass}>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="horizontal" className="text-xs">
                      horizontal
                    </SelectItem>
                    <SelectItem value="vertical" className="text-xs">
                      vertical
                    </SelectItem>
                  </SelectContent>
                </Select>
              </TemplateFieldGroup>

              {!scopeCatalogReady ? (
                <span className="min-w-0 flex-1 text-[11px] leading-tight text-[#1d3c8f]">
                  Loading company, region and location…
                </span>
              ) : (
                <CategoryScopeFields
                  layout="templateEditorInputGroup"
                  templateScopeMode
                  partners={filterPartners}
                  groups={filterGroups}
                  locations={locationCatalog}
                  selectedPartnerId=""
                  onPartnerChange={() => {}}
                  selectedPartnerIds={scopePartnerIds}
                  onPartnerIdsChange={setScopePartnerIds}
                  selectedRegionNames={[]}
                  onRegionChange={() => {}}
                  selectedRegionIds={scopeRegionIds}
                  onRegionIdsChange={setScopeRegionIds}
                  selectedLocationIds={scopeLocationIds}
                  onLocationChange={setScopeLocationIds}
                  requireCompanySelection={scopeAuth.requireCompanySelection}
                  fixedPartnerId={scopeAuth.fixedPartnerId}
                />
              )}
            </div>

            {loadingStarter ? (
              <div className="text-[11px] leading-tight text-[#1d3c8f]">Copying starter template…</div>
            ) : null}
          </div>
        </div>
      </div>

      {/* 三列:行布局内联;左侧整列 overflow-y:auto,保证橙色 Print input 可滚到 */}
      <div
        className="gap-2 bg-[#dde7f5] p-2"
        style={{
          flex: "1 1 0%",
          minHeight: 0,
          display: "flex",
          flexDirection: "row",
          alignItems: "stretch",
          gap: 8,
        }}
      >
        <div
          className="shrink-0 rounded-lg border border-[#c2d1e8] bg-[#e4ecf8] p-1"
          style={{
            width: "15rem",
            flexShrink: 0,
            alignSelf: "stretch",
            minHeight: 0,
            overflowX: "hidden",
            overflowY: "auto",
            WebkitOverflowScrolling: "touch",
            boxSizing: "border-box",
          }}
        >
          <ElementsPanel onAddElement={addElement} />
        </div>
        <div
          className="rounded-lg border border-[#c2d1e8] bg-[#e4ecf8] p-1"
          style={{
            flex: "1 1 0%",
            minHeight: 0,
            minWidth: 0,
            overflow: "hidden",
            display: "flex",
            flexDirection: "column",
          }}
        >
          <LabelCanvas
            template={template}
            selectedId={selectedId}
            onSelect={handleSelectElement}
            onUpdateElement={updateElement}
            onDeleteElement={deleteElement}
            onTemplateChange={handleTemplateChange}
            scale={scale}
            onZoomIn={() => setScale((s) => Math.min(MAX_SCALE, s + SCALE_STEP))}
            onZoomOut={() => setScale((s) => Math.max(MIN_SCALE, s - SCALE_STEP))}
            onResetZoom={() => setScale(DEFAULT_SCALE)}
            onPreview={() => setPreviewOpen(true)}
            hideToolbarPresetSize
            previewRulerUnit={previewRulerUnit}
            onPreviewRulerUnitChange={setPreviewRulerUnit}
            liveElementPatch={liveElementPatch}
            onLiveElementPatchChange={setLiveElementPatch}
            printOrientation={printOrientation}
            onPrintOrientationChange={handlePrintOrientationChange}
          />
        </div>
        <div
          className="rounded-lg border border-[#c2d1e8] bg-[#e4ecf8] p-1"
          style={{
            width: "18rem",
            flexShrink: 0,
            alignSelf: "stretch",
            minHeight: 0,
            overflow: "hidden",
            display: "flex",
            flexDirection: "column",
          }}
        >
          <div className="shrink-0 border-b border-[#c2d1e8] bg-white/80 px-2 py-2">
            <p className="mb-2 text-xs font-medium text-gray-700">Print preview</p>
            <div className="flex justify-center overflow-hidden">
              <LabelPreviewOnly
                template={previewTemplate}
                maxWidth={248}
                highlightElementId={selectedId}
                previewRulerUnit={previewRulerUnit}
                printOrientation={printOrientation}
              />
            </div>
          </div>
          <div className="min-h-0 flex-1 overflow-y-auto overflow-x-hidden">
            <PropertiesPanel
              template={template}
              selectedElement={selectedElement}
              onTemplateChange={handleTemplateChange}
              onElementChange={updateElement}
              onDeleteElement={deleteElement}
              readOnlyTemplateCode={!!templateId}
              previewRulerUnit={previewRulerUnit}
              printOrientation={printOrientation}
            />
          </div>
        </div>
      </div>
      <Dialog open={previewOpen} onOpenChange={setPreviewOpen}>
        <DialogContent className="max-w-[90vw] max-h-[90vh] p-0 overflow-hidden flex flex-col">
          <DialogHeader className="shrink-0 px-6 py-4 border-b bg-white">
            <DialogTitle>Label preview</DialogTitle>
          </DialogHeader>
          <div className="flex-1 min-h-0 overflow-x-auto overflow-y-auto p-4 bg-gray-50">
            <div className="min-w-max">
              <LabelPreviewOnly
                template={previewTemplate}
                highlightElementId={selectedId}
                previewRulerUnit={previewRulerUnit}
                printOrientation={printOrientation}
              />
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}