renderLabelPreviewCanvas.ts 42.3 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 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
import type { RawImageDataSource, SystemLabelTemplate, SystemTemplateElementBase } from '../print/types/printer'
import { resolveMediaUrlForApp, storedValueLooksLikeImagePath } from '../resolveMediaUrl'
import { sortElementsForPreview, normalizeTemplatePrintOrientation } from './normalizePreviewTemplate'
import { resolveLabelDesignCanvasPx } from '../print/templatePhysicalMm'
import {
  resolveElementDateTimeDisplay,
  isLikelyResolvedDateTimeLiteral,
  isCorruptedDateDisplayFormat,
  isStoredPrintInputOffsetPayload,
  sanitizeDateElementConfig,
  resolveWeekdayDisplayForElement,
  isUniAppDateTimeOffsetField,
  isWeekdayBarElement,
} from './printInputOffset'
import { getLoggedInEmployeeDisplayName, isEmployeeTemplateElement } from './employeeElement'
import QRCode from 'qrcode'
import { readInvertColors } from '../invertColorsConfig'
import {
  ensureLabelEditorFontsForTemplate,
  isLabelEditorFontItalicLoaded,
  resolveLabelEditorFontFamily,
} from '../labelEditorFonts'
import { computeVerticalTextBlockOffset, readVerticalAlign, readElementBorder, readFontStyle, readFontWeight, readTextDecoration, readElementRotation, type TextVerticalAlign } from '../textElementLayout'

import { computeImageDrawRect, readImageScaleMode } from '../imageScaleMode'
import {
  buildNutritionFactsViewModel,
  DEFAULT_NUTRITION_FOOTER_NOTE,
  NUTRITION_AMOUNT_COL_WIDTH,
  NUTRITION_BODY_FONT_SIZE,
  NUTRITION_PCT_COL_WIDTH,
  type NutritionDivider,
} from '../nutritionFactsLayout'

/** 与 Web LabelCanvas.unitToPx 一致:cm 用 37.8px/inch,保证与后台模板坐标系一致 */
const PX_PER_CM = 37.8
const PX_PER_INCH = 96

function toCanvasPx(value: number, unit: string): number {
  const u = String(unit || 'inch').toLowerCase()
  if (u === 'mm') return (value / 25.4) * PX_PER_INCH
  if (u === 'cm') return value * PX_PER_CM
  if (u === 'px') return value
  return value * PX_PER_INCH
}

function cfgStr(config: Record<string, any>, keys: string[], fallback = ''): string {
  for (const k of keys) {
    const v = config?.[k]
    if (v != null && v !== '') return String(v)
  }
  return fallback
}

/** 前缀在正文前;若正文已以前缀开头则不再重复拼接 */
function applyConfigPrefix(config: Record<string, any>, body: string): string {
  const prefix = String(config.prefix ?? config.Prefix ?? '')
  if (!prefix) return body
  const b = body ?? ''
  if (b.startsWith(prefix)) return b
  return `${prefix}${b}`
}

function readFontSize(config: Record<string, any>): number {
  const n = Number(config.fontSize ?? config.FontSize ?? 14)
  return Math.max(6, Math.round(Number.isFinite(n) ? n : 14))
}

function readTextAlign(config: Record<string, any>): string {
  return String(config.textAlign ?? config.TextAlign ?? 'left').toLowerCase()
}

function readFillColor(config: Record<string, any>): string {
  return String(config.color ?? config.Color ?? '#111827')
}

/** 底部黑条:模板约定 verticalAlign=center,在元素框内居中铺黑底(与 Web flex 一致) */
function resolveDrawVerticalAlign(
  config: Record<string, any>,
  el: SystemTemplateElementBase,
  opts: { invertedBar: boolean; weekdayBar: boolean },
): TextVerticalAlign {
  const merged = {
    ...config,
    verticalAlign:
      config.verticalAlign
      ?? config.VerticalAlign
      ?? (el as Record<string, unknown>).verticalAlign
      ?? (el as Record<string, unknown>).VerticalAlign,
  }
  const align = readVerticalAlign(merged)
  if (opts.invertedBar && opts.weekdayBar) {
    if (align === 'top') return 'center'
    return align
  }
  return align
}

function lineHeightForTextElement(
  printFontSize: number,
  isDateTimeType: boolean,
): number {
  return isDateTimeType
    ? Math.max(printFontSize + 2, Math.round(printFontSize * 1.2))
    : Math.max(printFontSize + 2, Math.round(printFontSize * 1.25))
}

/**
 * Web AlignedTextBox + 黑底行:行盒高度略小于 line-height 1.2,在元素框内垂直居中。
 * layout 用较薄行盒算偏移,绘制用略高条带承托粗体。
 */
function layoutInvertedWeekdayStrip(
  by: number,
  bh: number,
  printFontSize: number,
  verticalAlign: TextVerticalAlign,
): { stripTop: number; stripHeight: number; textY: number } {
  const layoutH = Math.max(printFontSize + 2, Math.round(printFontSize * 1.12))
  const stripHeight = Math.max(layoutH, Math.round(printFontSize * 1.22))
  const effectiveAlign = verticalAlign === 'top' ? 'center' : verticalAlign
  const verticalOffset = computeVerticalTextBlockOffset(bh, layoutH, effectiveAlign)
  const stripTop = by + verticalOffset
  const textY = stripTop + Math.round(stripHeight * 0.74)
  return { stripTop, stripHeight, textY }
}

/** 矮框 TIME(如 h=16):文字贴上沿,避免下沉侵占黑条上边距 */
function textYForShortTimeBox(by: number, bh: number, printFontSize: number): number {
  const lineTop = by + Math.max(0, Math.floor((bh - printFontSize) * 0.08))
  return lineTop + Math.round(printFontSize * 0.72)
}

function applyCanvasFontFromConfig(
  ctx: UniApp.CanvasContext,
  config: Record<string, any>,
  fontSize: number,
): void {
  const fontFamily = resolveLabelEditorFontFamily(config)
  const anyCtx = ctx as any
  const weight = readFontWeight(config) === 'bold' ? 'bold' : 'normal'
  const style = readFontStyle(config) === 'italic' ? 'italic' : 'normal'
  if (typeof anyCtx.setFontFamily === 'function') {
    anyCtx.setFontFamily(fontFamily)
  }
  if (typeof anyCtx.setFontWeight === 'function') {
    anyCtx.setFontWeight(weight)
  }
  if (typeof anyCtx.font !== 'undefined') {
    anyCtx.font = `${style} ${weight} ${fontSize}px "${fontFamily}"`
  }
}

function approxTextWidth(text: string, fontSize: number): number {
  return Math.max(4, String(text).length * fontSize * 0.55)
}

function drawStyledTextLine(
  ctx: UniApp.CanvasContext,
  line: string,
  tx: number,
  y: number,
  fontSize: number,
  align: string,
  config: Record<string, any>,
  fillColor: string,
  emphasizeForPrint = false,
): void {
  const family = resolveLabelEditorFontFamily(config)
  const italic = readFontStyle(config) === 'italic'
  const underline = readTextDecoration(config) === 'underline'
  const useSkewFallback = italic && !isLabelEditorFontItalicLoaded(family)
  const anyCtx = ctx as any
  const lineWidth = approxTextWidth(line, fontSize)

  const drawFill = () => {
    if (emphasizeForPrint) {
      const stroke = Math.max(0.5, fontSize * 0.04)
      for (const [ox, oy] of [[0, 0], [stroke, 0], [-stroke, 0], [0, stroke], [0, -stroke]] as const) {
        ctx.fillText(line, tx + ox, y + oy)
      }
      return
    }
    ctx.fillText(line, tx, y)
  }

  if (useSkewFallback && typeof anyCtx.save === 'function') {
    anyCtx.save()
    anyCtx.transform(1, 0, -0.25, 1, tx * 0.08, 0)
  }
  drawFill()
  if (underline) {
    let x1 = tx
    let x2 = tx + lineWidth
    if (align === 'center') {
      x1 = tx - lineWidth / 2
      x2 = tx + lineWidth / 2
    } else if (align === 'right') {
      x1 = tx - lineWidth
      x2 = tx
    }
    ctx.setStrokeStyle(fillColor)
    ctx.setLineWidth(Math.max(1, Math.round(fontSize * 0.06)))
    ctx.beginPath()
    ctx.moveTo(x1, y + Math.max(1, Math.round(fontSize * 0.12)))
    ctx.lineTo(x2, y + Math.max(1, Math.round(fontSize * 0.12)))
    ctx.stroke()
  }
  if (useSkewFallback && typeof anyCtx.restore === 'function') {
    anyCtx.restore()
  }
}

/** 按元素框宽度估算每行最大字符数(等宽近似,兼容中英文) */
function maxCharsPerLine(innerWidthPx: number, fontSize: number): number {
  if (innerWidthPx <= 4) return 8
  const approx = Math.max(0.45, Math.min(0.75, 0.55))
  /** 下限 8:避免过窄估算时按 4 字硬切把英文单词拦腰截断(如 All|ergens) */
  return Math.max(8, Math.floor(innerWidthPx / (fontSize * approx)))
}

/**
 * 优先在空格处断行,长词再按字符切分;避免固定宽度硬切破坏英文单词与「标签: 值」可读性。
 */
function wrapSingleLogicalLine(line: string, maxChars: number): string[] {
  const limit = Math.max(8, maxChars)
  const s = String(line)
  if (s.length <= limit) return [s]

  const words = s.split(/(\s+)/)
  const out: string[] = []
  let cur = ''

  const pushLongToken = (token: string) => {
    for (let i = 0; i < token.length; i += limit) {
      out.push(token.slice(i, i + limit))
    }
  }

  for (const w of words) {
    if (/^\s+$/.test(w)) {
      cur += w
      continue
    }
    if (!w) continue

    const trimmedRight = cur.replace(/\s+$/, '')
    const candidate = trimmedRight ? `${trimmedRight} ${w}` : w
    if (candidate.length <= limit) {
      cur = candidate
    } else {
      if (trimmedRight) out.push(trimmedRight)
      cur = ''
      if (w.length > limit) {
        pushLongToken(w)
      } else {
        cur = w
      }
    }
  }
  const tail = cur.replace(/\s+$/, '')
  if (tail) out.push(tail)
  return out.length ? out : ['']
}

function wrapTextToWidth(text: string, maxChars: number): string[] {
  const lines = String(text).split(/\r?\n/)
  const out: string[] = []
  for (const line of lines) {
    out.push(...wrapSingleLogicalLine(line, maxChars))
  }
  return out.length ? out : ['']
}

function resolveDateTimePreviewText (
  element: SystemTemplateElementBase,
  baseTime: Date = new Date(),
): string {
  if (isWeekdayBarElement(element)) {
    return applyConfigPrefix(
      element.config || {},
      resolveWeekdayDisplayForElement(element, baseTime),
    )
  }
  const config = element.config || {}
  const previewFormatted = cfgStr(config, ['__previewFormatted', '__PreviewFormatted'], '').trim()
  if (
    previewFormatted &&
    !isCorruptedDateDisplayFormat(previewFormatted) &&
    !isStoredPrintInputOffsetPayload(previewFormatted)
  ) {
    return applyConfigPrefix(config, previewFormatted)
  }
  const sanitizedCfg = { ...config } as Record<string, unknown>
  sanitizeDateElementConfig(element, sanitizedCfg)
  try {
    const live = resolveElementDateTimeDisplay({ ...element, config: sanitizedCfg }, baseTime)
    if (live != null && live.trim() && !isCorruptedDateDisplayFormat(live) && !isStoredPrintInputOffsetPayload(live)) {
      return applyConfigPrefix(sanitizedCfg, live)
    }
  } catch (err) {
    console.warn('[labelPreview] resolveElementDateTimeDisplay failed', element.id, err)
  }
  return ''
}

function previewTextForElement(element: SystemTemplateElementBase, baseTime: Date = new Date()): string {
  const type = String(element.type || '').toUpperCase()
  const config = element.config || {}
  if (isWeekdayBarElement(element)) {
    return applyConfigPrefix(config, resolveWeekdayDisplayForElement(element, baseTime))
  }
  if (isEmployeeTemplateElement(element)) {
    const cfgText = cfgStr(config, ['text', 'Text'], '').trim()
    if (cfgText && cfgText.toLowerCase() !== 'text') return applyConfigPrefix(config, cfgText)
    return applyConfigPrefix(config, getLoggedInEmployeeDisplayName())
  }
  if (type === 'DATE' || type === 'TIME' || type === 'DURATION') {
    return resolveDateTimePreviewText(element, baseTime)
  }
  if (type === 'QRCODE') {
    return cfgStr(config, ['data', 'Data', 'value', 'Value'])
  }
  if (type === 'BARCODE') {
    // 平台模板条码值常见键:data / barcodeData(含大小写变体)
    return cfgStr(config, ['data', 'Data', 'barcodeData', 'BarcodeData', 'value', 'Value'])
  }
  const vst = String(element.valueSourceType || '').toUpperCase()
  const inputType = String(config.inputType ?? config.InputType ?? '').toLowerCase()
  const hasDict = !!(config.multipleOptionId ?? config.MultipleOptionId)
  if (vst === 'PRINT_INPUT' && (inputType === 'options' || hasDict)) {
    const rawSel = config.selectedOptionValues ?? config.SelectedOptionValues
    const arr = Array.isArray(rawSel) ? rawSel.map((x: unknown) => String(x)) : []
    const txt = cfgStr(config, ['text', 'Text'], '')
    if (arr.length > 0 && txt.trim()) return txt
    if (arr.length > 0) {
      const joined = arr.join(', ')
      return applyConfigPrefix(config, joined)
    }
    const hint = txt.trim() || 'Select below'
    return applyConfigPrefix(config, hint)
  }
  if (vst === 'PRINT_INPUT' && !(inputType === 'options' || hasDict)) {
    if (
      inputType === 'date' ||
      inputType === 'datetime' ||
      isUniAppDateTimeOffsetField(element)
    ) {
      return resolveDateTimePreviewText(element, baseTime)
    }
    let body = cfgStr(config, ['text', 'Text'], '')
    if (!body.trim()) body = cfgStr(config, ['value', 'Value'], '')
    if (!body.trim()) body = cfgStr(config, ['format', 'Format', 'placeholder', 'Placeholder'], '')
    if (isStoredPrintInputOffsetPayload(body) || isCorruptedDateDisplayFormat(body)) return ''
    const unit = String(config.unit ?? config.Unit ?? '').trim()
    if (unit && body.trim() && !body.endsWith(unit)) body = `${body}${unit}`
    return applyConfigPrefix(config, body)
  }
  const body = cfgStr(config, [
    'text',
    'Text',
    'format',
    'Format',
    'content',
    'Content',
    'value',
    'Value',
    'displayText',
    'displayValue',
    'defaultValue',
    'placeholder',
  ])
  if (isStoredPrintInputOffsetPayload(body) || isCorruptedDateDisplayFormat(body)) return ''
  return applyConfigPrefix(config, body)
}

function isGraphicOnlyType(type: string): boolean {
  return type === 'IMAGE' || type === 'LOGO' || type === 'BARCODE' || type === 'QRCODE'
}

function previewExportPixelRatio(): number {
  try {
    const pr = uni.getSystemInfoSync().pixelRatio
    return Math.min(2.5, Math.max(1, typeof pr === 'number' && pr > 0 ? pr : 2))
  } catch {
    return 2
  }
}

function barcodeModulesFromValue(value: string): number[] {
  const s = String(value || '').trim()
  if (!s) return []
  const modules: number[] = []
  // quiet + start(轻量预览编码:保证视觉稳定,非扫描级编码)
  modules.push(1, 0, 1, 0, 1, 0, 1, 0)
  for (let i = 0; i < s.length; i++) {
    const code = s.charCodeAt(i) & 0xff
    // 用 5bit 模块 + 分隔位,避免在窄宽度里“整块发黑”。
    const key = (code ^ (i * 13) ^ (s.length * 7)) & 0x1f
    for (let b = 4; b >= 0; b--) modules.push((key >> b) & 1)
    modules.push(0)
  }
  // stop
  modules.push(1, 0, 1, 1, 0, 1, 0, 1)
  return modules
}

function drawBarcodeLikePreview(
  ctx: UniApp.CanvasContext,
  x: number,
  y: number,
  w: number,
  h: number,
  value: string,
  options?: { orientation?: string; showText?: boolean }
): void {
  const bw = Math.max(40, w || 140)
  const bh = Math.max(28, h || 56)
  const showText = options?.showText !== false
  const pad = 2
  const modules = barcodeModulesFromValue(value)
  const orientation = String(options?.orientation || 'horizontal').toLowerCase()
  const isVertical = orientation === 'vertical'

  ctx.setFillStyle('#ffffff')
  ctx.fillRect(x, y, bw, bh)
  if (!modules.length) return

  const txt = String(value || '').trim()
  ctx.setFillStyle('#111827')

  if (!isVertical) {
    const textH = showText && txt ? Math.max(10, Math.round(bh * 0.2)) : 0
    const barH = Math.max(10, bh - textH - pad * 2)
    const innerW = Math.max(8, bw - pad * 2)
    const moduleW = innerW / modules.length
    let cursor = x + pad
    for (let i = 0; i < modules.length; i++) {
      if (modules[i] === 1) {
        const rw = Math.max(0.7, moduleW * 0.72)
        ctx.fillRect(cursor, y + pad, rw, barH)
      }
      cursor += moduleW
    }
    if (showText && txt) {
      ctx.setFontSize(Math.max(9, Math.min(12, Math.round(textH * 0.8))))
      ctx.setTextAlign('center')
      ctx.fillText(txt, x + bw / 2, y + bh - 2)
      ctx.setTextAlign('left')
    }
    return
  }

  // vertical:条码在左,data 竖排在右
  const textBandW = showText && txt ? Math.max(10, Math.round(bw * 0.18)) : 0
  const barW = Math.max(10, bw - textBandW - pad * 2)
  const innerH = Math.max(10, bh - pad * 2)
  const moduleH = innerH / modules.length
  let cursorY = y + pad
  for (let i = 0; i < modules.length; i++) {
    if (modules[i] === 1) {
      const rh = Math.max(0.7, moduleH * 0.72)
      ctx.fillRect(x + pad, cursorY, barW, rh)
    }
    cursorY += moduleH
  }
  if (showText && txt) {
    const font = Math.max(9, Math.min(11, Math.floor(textBandW * 0.75)))
    const cx = x + bw - textBandW / 2
    const cy = y + bh / 2
    const anyCtx = ctx as any
    if (typeof anyCtx.save === 'function' && typeof anyCtx.rotate === 'function') {
      anyCtx.save()
      anyCtx.translate(cx, cy)
      // 竖排文本按模板端习惯:从下到上
      anyCtx.rotate(-Math.PI / 2)
      ctx.setFontSize(font)
      ctx.setTextAlign('center')
      ctx.fillText(txt, 0, Math.min(font * 0.35, 4))
      ctx.setTextAlign('left')
      anyCtx.restore()
    } else {
      // 低端环境兜底:不旋转能力时退化为逐字竖排
      let ty = y + pad + font
      ctx.setFontSize(font)
      ctx.setTextAlign('center')
      for (let i = 0; i < txt.length; i++) {
        ctx.fillText(txt[i], cx, ty)
        ty += font + 1
        if (ty > y + bh - 1) break
      }
      ctx.setTextAlign('left')
    }
  }
}

function drawQrCodePreview(
  ctx: UniApp.CanvasContext,
  x: number,
  y: number,
  w: number,
  h: number,
  value: string,
  errorLevelRaw?: string,
): void {
  const text = String(value || '').trim()
  const bw = Math.max(24, w || 96)
  const bh = Math.max(24, h || 96)
  if (!text) return

  let matrixSize = 0
  let moduleData: Uint8Array | number[] = []
  try {
    const lv = String(errorLevelRaw || 'M').trim().toUpperCase()
    const level = lv === 'L' || lv === 'M' || lv === 'Q' || lv === 'H' ? lv : 'M'
    const qr = QRCode.create(text, { errorCorrectionLevel: level })
    matrixSize = Number(qr?.modules?.size || 0)
    moduleData = (qr?.modules?.data as Uint8Array | number[]) || []
  } catch {
    matrixSize = 0
    moduleData = []
  }
  if (!matrixSize || !moduleData.length) return

  const pad = Math.max(1, Math.floor(Math.min(bw, bh) * 0.06))
  const side = Math.max(12, Math.min(bw, bh) - pad * 2)
  const cell = Math.max(1, Math.floor(side / matrixSize))
  const drawSide = cell * matrixSize
  const ox = x + Math.floor((bw - drawSide) / 2)
  const oy = y + Math.floor((bh - drawSide) / 2)

  ctx.setFillStyle('#ffffff')
  ctx.fillRect(x, y, bw, bh)
  ctx.setFillStyle('#111827')
  for (let r = 0; r < matrixSize; r++) {
    for (let c = 0; c < matrixSize; c++) {
      const idx = r * matrixSize + c
      const dark = Number((moduleData as any)[idx]) === 1
      if (!dark) continue
      ctx.fillRect(ox + c * cell, oy + r * cell, cell, cell)
    }
  }
}


/** 双下划线两线间距(px),与 Web NutritionFactsPanel 一致 */
const NUTRITION_DOUBLE_LINE_GAP = 3

function drawNutritionDivider(
  ctx: UniApp.CanvasContext,
  x1: number,
  x2: number,
  y: number,
  kind: NutritionDivider,
): number {
  if (kind === 'none') return 0
  ctx.setStrokeStyle('#111827')
  ctx.setLineWidth(1)
  if (kind === 'double') {
    ctx.beginPath()
    ctx.moveTo(x1, y)
    ctx.lineTo(x2, y)
    ctx.stroke()
    const y2 = y + 1 + NUTRITION_DOUBLE_LINE_GAP
    ctx.beginPath()
    ctx.moveTo(x1, y2)
    ctx.lineTo(x2, y2)
    ctx.stroke()
    return 1 + NUTRITION_DOUBLE_LINE_GAP + 1 + 2
  }
  ctx.beginPath()
  ctx.moveTo(x1, y)
  ctx.lineTo(x2, y)
  ctx.stroke()
  return 2
}

function drawNutritionFactsOnCanvas(
  ctx: UniApp.CanvasContext,
  config: Record<string, any>,
  boxX: number,
  boxY: number,
  boxW: number,
  boxH: number,
): void {
  const model = buildNutritionFactsViewModel(config)
  const pad = 6
  const leftX = boxX + pad
  const rightX = boxX + boxW - pad
  const amountColRight = rightX - NUTRITION_PCT_COL_WIDTH
  const amountX = amountColRight - NUTRITION_AMOUNT_COL_WIDTH / 2
  const pctX = rightX
  const maxY = boxY + boxH - pad
  let cursorY = boxY + pad
  const titleSize = Math.max(11, Math.min(18, model.titleFontSize))
  const bodySize = NUTRITION_BODY_FONT_SIZE
  const footerSize = Math.max(8, Math.round(bodySize * 0.67))
  /** 正文用 Roboto,避免 FreightSans Bold 导致整表加粗(与 Web 一致) */
  const bodyCfg = { ...config, fontFamily: 'Roboto', FontFamily: 'Roboto' }

  ctx.setFillStyle('#ffffff')
  ctx.fillRect(boxX, boxY, boxW, boxH)

  const rowStep = (fs: number) => fs + 4

  const drawLine = (label: string, value: string, fs: number, labelBold = false) => {
    const f = Math.max(8, Math.round(fs))
    const lh = rowStep(f)
    if (cursorY + lh > maxY) return false
    ctx.setFillStyle('#111827')
    ctx.setFontSize(f)
    applyCanvasFontFromConfig(ctx, { ...bodyCfg, fontWeight: labelBold ? 'bold' : 'normal' }, f)
    ctx.setTextAlign('left')
    ctx.fillText(label, leftX, cursorY + f)
    if (value) {
      applyCanvasFontFromConfig(ctx, { ...bodyCfg, fontWeight: 'normal' }, f)
      ctx.setTextAlign('right')
      ctx.fillText(value, rightX, cursorY + f)
    }
    cursorY += lh
    return true
  }

  const drawNutrientRow = (
    label: string,
    amount: string,
    pct: string,
    fs: number,
    labelBold: boolean,
    indent: boolean,
    divider: NutritionDivider,
  ) => {
    const f = Math.max(8, Math.round(fs))
    const lh = rowStep(f)
    if (cursorY + lh > maxY) return false
    const labelX = leftX + (indent ? 10 : 0)
    ctx.setFillStyle('#111827')
    ctx.setFontSize(f)
    applyCanvasFontFromConfig(ctx, { ...bodyCfg, fontWeight: labelBold ? 'bold' : 'normal' }, f)
    ctx.setTextAlign('left')
    ctx.fillText(label, labelX, cursorY + f)
    applyCanvasFontFromConfig(ctx, { ...bodyCfg, fontWeight: 'normal' }, f)
    if (amount) {
      ctx.setTextAlign('center')
      ctx.fillText(amount, amountX, cursorY + f)
    }
    if (pct) {
      ctx.setTextAlign('right')
      ctx.fillText(pct, pctX, cursorY + f)
    }
    cursorY += lh
    if (divider !== 'none') {
      cursorY += drawNutritionDivider(ctx, leftX, rightX, cursorY, divider)
    }
    return true
  }

  const drawFooterNote = () => {
    if (cursorY + footerSize + 6 > maxY) return
    cursorY += drawNutritionDivider(ctx, leftX, rightX, cursorY, 'thin')
    ctx.setFontSize(footerSize)
    ctx.setTextAlign('left')
    const parts = DEFAULT_NUTRITION_FOOTER_NOTE.split(/(\b2000\b)/)
    let fx = leftX
    for (const part of parts) {
      if (!part) continue
      applyCanvasFontFromConfig(
        ctx,
        { ...bodyCfg, fontWeight: part === '2000' ? 'bold' : 'normal' },
        footerSize,
      )
      ctx.fillText(part, fx, cursorY + footerSize)
      fx += approxTextWidth(part, footerSize)
    }
    cursorY += footerSize + 2
  }

  ctx.setFillStyle('#111827')
  ctx.setFontSize(Math.round(titleSize))
  applyCanvasFontFromConfig(ctx, { ...config, fontWeight: 'bold' }, titleSize)
  ctx.setTextAlign('left')
  ctx.fillText('Nutrition Facts', leftX, cursorY + titleSize)
  cursorY += titleSize + 1
  cursorY += drawNutritionDivider(ctx, leftX, rightX, cursorY, 'double')

  drawLine(model.servingsLabel, model.servingsValue, bodySize)
  cursorY += drawNutritionDivider(ctx, leftX, rightX, cursorY, 'thin')
  drawLine(model.servingSizeLabel, model.servingSizeValue, bodySize)
  cursorY += drawNutritionDivider(ctx, leftX, rightX, cursorY, 'double')

  if (cursorY + bodySize + 3 <= maxY) {
    ctx.setFontSize(bodySize)
    applyCanvasFontFromConfig(ctx, { ...bodyCfg, fontWeight: 'bold' }, bodySize)
    ctx.setTextAlign('left')
    ctx.fillText(model.caloriesLabel, leftX, cursorY + bodySize)
    applyCanvasFontFromConfig(ctx, { ...bodyCfg, fontWeight: 'normal' }, bodySize)
    ctx.setTextAlign('right')
    ctx.fillText(model.caloriesAmountText || model.caloriesValue, rightX, cursorY + bodySize)
    cursorY += bodySize + 1
    cursorY += drawNutritionDivider(ctx, leftX, rightX, cursorY, 'double')
  }

  for (const row of model.rows) {
    if (
      !drawNutrientRow(
        row.label,
        row.amountText,
        row.dailyValueText,
        bodySize,
        row.labelBold,
        row.indent,
        row.dividerAfter,
      )
    ) {
      break
    }
  }

  drawFooterNote()
}

function strokeTemplatePaperBorder (
  ctx: UniApp.CanvasContext,
  template: SystemLabelTemplate,
  cw: number,
  ch: number
) {
  const border = String(template.border || '').toLowerCase()
  if (border !== 'line' && border !== 'dotted') return
  ctx.setStrokeStyle('#374151')
  ctx.setLineWidth(2)
  const w = Math.max(0, cw - 1)
  const h = Math.max(0, ch - 1)
  if (border === 'dotted' && typeof (ctx as any).setLineDash === 'function') {
    ;(ctx as any).setLineDash([4, 3], 0)
    ctx.strokeRect(1, 1, w - 1, h - 1)
    ;(ctx as any).setLineDash([], 0)
  } else {
    ctx.strokeRect(1, 1, w - 1, h - 1)
  }
}

/** 元素级边框:须在背景/文字之后绘制,避免被 invert 黑底盖住 */
function strokeElementBorder(
  ctx: UniApp.CanvasContext,
  x: number,
  y: number,
  w: number,
  h: number,
  border: string | undefined,
) {
  const line = String(border || '').toLowerCase()
  if (line !== 'line' && line !== 'solid' && line !== 'dotted') return
  ctx.setStrokeStyle(line === 'dotted' ? '#9ca3af' : '#111827')
  ctx.setLineWidth(1)
  if (line === 'dotted' && typeof (ctx as any).setLineDash === 'function') {
    ;(ctx as any).setLineDash([3, 3], 0)
    ctx.strokeRect(x, y, w, h)
    ;(ctx as any).setLineDash([], 0)
  } else {
    ctx.strokeRect(x, y, w, h)
  }
}

/** 横打:与 Web printContentLayerStyle rotate(90deg) 一致,纸张尺寸不变 */
function applyPrintContentRotation(ctx: UniApp.CanvasContext, cw: number, ch: number): void {
  const cx = cw / 2
  const cy = ch / 2
  ctx.translate(cx, cy)
  ctx.rotate(Math.PI / 2)
  ctx.translate(-cx, -cy)
}

/** 与屏幕预览 / 位图打印共用绘制逻辑(坐标系:设计宽 cw × ch,ctx 已 scale) */
function runLabelPreviewCanvasDraw(
  canvasId: string,
  componentInstance: any,
  template: SystemLabelTemplate,
  cw: number,
  ch: number,
  scale: number,
  drawOptions: { forPrint?: boolean; baseTime?: Date } = {},
): Promise<void> {
  const forPrint = drawOptions.forPrint === true
  const baseTime = drawOptions.baseTime ?? new Date()
  const sorted = sortElementsForPreview(template.elements || [])
  const rotateContent = normalizeTemplatePrintOrientation(template.printOrientation) === 'horizontal'

  return ensureLabelEditorFontsForTemplate(template).then(
    () =>
      new Promise((resolve) => {
    const ctx = uni.createCanvasContext(canvasId, componentInstance)
    ctx.setFillStyle('#ffffff')
    ctx.scale(scale, scale)
    ctx.fillRect(0, 0, cw, ch)
    if (rotateContent) {
      ctx.save()
      applyPrintContentRotation(ctx, cw, ch)
    }

    const drawRest = (index: number) => {
      if (index >= sorted.length) {
        if (rotateContent) {
          ctx.restore()
        }
        strokeTemplatePaperBorder(ctx, template, cw, ch)
        ctx.draw(false, () => resolve())
        return
      }

      const el = sorted[index]
      const type = String(el.type || '').toUpperCase()
      const config = el.config || {}
      const x = Number(el.x) || 0
      const y = Number(el.y) || 0
      const w = Math.max(0, Number(el.width) || 0)
      const h = Math.max(0, Number(el.height) || 0)

      const next = () => drawRest(index + 1)
      const finishElement = () => {
        strokeElementBorder(ctx, x, y, w, h, readElementBorder(el))
        next()
      }

      if (type === 'IMAGE' || type === 'LOGO') {
        const src = resolveMediaUrlForApp(cfgStr(config, ['src', 'url', 'Src', 'Url']))
        const boxW = w || 80
        const boxH = h || 40
        const scaleMode = readImageScaleMode(config)
        if (src) {
          uni.getImageInfo({
            src,
            success: (info) => {
              try {
                const rect = computeImageDrawRect(
                  boxW,
                  boxH,
                  Number(info.width) || 0,
                  Number(info.height) || 0,
                  scaleMode,
                )
                ctx.drawImage(info.path, x + rect.dx, y + rect.dy, rect.dw, rect.dh)
              } catch (_) {
                ctx.setStrokeStyle('#cccccc')
                ctx.setLineWidth(1)
                ctx.strokeRect(x, y, boxW, boxH)
              }
              finishElement()
            },
            fail: () => {
              ctx.setStrokeStyle('#cccccc')
              ctx.strokeRect(x, y, boxW, boxH)
              finishElement()
            },
          })
          return
        }
        finishElement()
        return
      }

      if (type === 'NUTRITION') {
        drawNutritionFactsOnCanvas(ctx, config, x, y, Math.max(40, w || 220), Math.max(80, h || 280))
        finishElement()
        return
      }

      if (type === 'QRCODE' || type === 'BARCODE') {
        const d = previewTextForElement(el)
        const drawQrBarcodePlaceholder = () => {
          ctx.setFillStyle('#f3f4f6')
          ctx.fillRect(x, y, w || 60, h || 60)
          ctx.setStrokeStyle('#9ca3af')
          ctx.setLineWidth(1)
          ctx.strokeRect(x, y, w || 60, h || 60)
          ctx.setFillStyle('#374151')
          ctx.setFontSize(10)
          const label = type === 'QRCODE' ? 'QR' : 'BC'
          ctx.fillText(label, x + 4, y + 14)
          if (d) {
            const short = d.length > 12 ? `${d.slice(0, 10)}…` : d
            ctx.fillText(short, x + 4, y + 28)
          }
        }

        if (type === 'BARCODE' && d) {
          const elementRotation = readElementRotation(el)
          const configOrientation = cfgStr(config, ['orientation', 'Orientation'], 'horizontal').toLowerCase()
          const orientation = elementRotation === 'vertical' ? 'vertical' : configOrientation
          const showText = String(config.showText ?? config.ShowText ?? 'true').toLowerCase() !== 'false'
          drawBarcodeLikePreview(ctx, x, y, w || 140, h || 56, d, { orientation, showText })
          finishElement()
          return
        }

        if (type === 'QRCODE' && d && !storedValueLooksLikeImagePath(d)) {
          drawQrCodePreview(ctx, x, y, w || 96, h || 96, d, cfgStr(config, ['errorLevel', 'ErrorLevel'], 'M'))
          finishElement()
          return
        }

        // 管理端可把二维码默认值存为上传图片路径,须按位图绘制而非占位符文本
        if (type === 'QRCODE' && d && storedValueLooksLikeImagePath(d)) {
          const src = resolveMediaUrlForApp(d)
          if (src) {
            uni.getImageInfo({
              src,
              success: (info) => {
                try {
                  const dw = w || info.width
                  const dh = h || info.height
                  ctx.drawImage(info.path, x, y, dw, dh)
                } catch (_) {
                  drawQrBarcodePlaceholder()
                }
                finishElement()
              },
              fail: () => {
                drawQrBarcodePlaceholder()
                finishElement()
              },
            })
            return
          }
        }

        drawQrBarcodePlaceholder()
        finishElement()
        return
      }

      const weekdayBar = isWeekdayBarElement(el)
      let finalText = ''
      if (weekdayBar) {
        try {
          finalText = resolveWeekdayDisplayForElement(el, baseTime)
        } catch (err) {
          console.warn('[labelPreview] resolveWeekdayDisplayForElement failed', el.id, err)
        }
      } else {
        try {
          finalText = previewTextForElement(el, baseTime)
        } catch (err) {
          console.warn('[labelPreview] previewTextForElement failed', el.id, err)
        }
        if (finalText && isCorruptedDateDisplayFormat(finalText)) {
          finalText = ''
        }
      }
      if ((finalText || weekdayBar) && !isGraphicOnlyType(type)) {
        if (!finalText && weekdayBar) {
          finalText = resolveWeekdayDisplayForElement(el, baseTime)
        }
        const rotation = String(el.rotation ?? (el as any).Rotation ?? 'horizontal').toLowerCase()
        const drawAt = (bx: number, by: number, bw: number, bh: number) => {
          const anyCtx = ctx as any
          if (typeof anyCtx.save === 'function') anyCtx.save()
          if (typeof anyCtx.beginPath === 'function' && typeof anyCtx.rect === 'function') {
            anyCtx.beginPath()
            anyCtx.rect(bx, by, bw, bh)
            if (typeof anyCtx.clip === 'function') anyCtx.clip()
          }

          const fontSize = readFontSize(config)
          const invertedBar = readInvertColors(config)
          const printFontSize = invertedBar && forPrint ? fontSize + Math.max(1, Math.round(fontSize * 0.08)) : fontSize
          ctx.setFontSize(printFontSize)
          applyCanvasFontFromConfig(ctx, config, printFontSize)
          const fontWeight = invertedBar && forPrint ? 'bold' : readFontWeight(config)
          if (typeof anyCtx.setFontWeight === 'function') {
            anyCtx.setFontWeight(fontWeight === 'bold' ? 'bold' : 'normal')
          }
          const align = readTextAlign(config)
          const fillColor = invertedBar ? '#ffffff' : readFillColor(config)
          /** 与 Web AlignedTextBox 的 Tailwind px-1 一致:仅水平 4px,垂直无 padding */
          const hPad = 4
          const innerW = Math.max(0, bw - hPad * 2)
          const innerH = Math.max(printFontSize, bh)
          let tx = bx + hPad
          if (align === 'center') tx = bx + bw / 2
          else if (align === 'right') tx = bx + bw - hPad
          ctx.setTextAlign(align === 'center' ? 'center' : align === 'right' ? 'right' : 'left')
          const isDateTimeType = type === 'DATE' || type === 'TIME' || type === 'DURATION' || weekdayBar
          const lineHeight = lineHeightForTextElement(printFontSize, isDateTimeType)
          const lines = isDateTimeType
            ? [String(finalText).replace(/\s+/g, ' ').trim()]
            : wrapTextToWidth(finalText, maxCharsPerLine(innerW, printFontSize))
          const layoutBoxH = invertedBar ? bh : innerH
          const fittedLineHeight =
            isDateTimeType && !invertedBar && bh > 0 ? Math.min(lineHeight, bh) : lineHeight
          const maxLines = isDateTimeType
            ? 1
            : layoutBoxH >= printFontSize
              ? Math.max(1, Math.floor(layoutBoxH / fittedLineHeight))
              : lines.length
          const visibleLines = lines.slice(0, maxLines)
          const blockHeight = visibleLines.length * fittedLineHeight
          const verticalAlign = resolveDrawVerticalAlign(config, el, { invertedBar, weekdayBar })
          const verticalOffset = computeVerticalTextBlockOffset(layoutBoxH, blockHeight, verticalAlign)
          const lineTop = by + verticalOffset
          const baselineFromLineTop = Math.round(printFontSize * 0.82)
          const defaultStartY = lineTop + baselineFromLineTop
          const shortTimeBox = type === 'TIME' && !invertedBar && bh > 0 && bh <= 20
          const weekdayStrip = invertedBar && weekdayBar
            ? layoutInvertedWeekdayStrip(by, bh, printFontSize, verticalAlign)
            : null

          if (weekdayStrip) {
            ctx.setFillStyle('#000000')
            ctx.fillRect(bx + hPad, weekdayStrip.stripTop, innerW, weekdayStrip.stripHeight)
            ctx.setFillStyle('#ffffff')
          } else if (invertedBar) {
            ctx.setFillStyle('#000000')
            ctx.fillRect(bx + hPad, lineTop, innerW, blockHeight)
            ctx.setFillStyle('#ffffff')
          } else {
            ctx.setFillStyle(fillColor)
          }

          visibleLines.forEach((ln, li) => {
            const textY = weekdayStrip
              ? weekdayStrip.textY + li * weekdayStrip.stripHeight
              : shortTimeBox
                ? textYForShortTimeBox(by, bh, printFontSize) + li * fittedLineHeight
                : defaultStartY + li * fittedLineHeight
            drawStyledTextLine(
              ctx,
              ln,
              tx,
              textY,
              printFontSize,
              align,
              config,
              fillColor,
              invertedBar && forPrint,
            )
          })
          ctx.setTextAlign('left')
          if (typeof anyCtx.restore === 'function') anyCtx.restore()
        }

        if (rotation === 'vertical') {
          const anyCtx = ctx as any
          if (typeof anyCtx.save === 'function' && typeof anyCtx.rotate === 'function') {
            anyCtx.save()
            anyCtx.translate(x + w / 2, y + h / 2)
            anyCtx.rotate(-Math.PI / 2)
            drawAt(-h / 2, -w / 2, h, w)
            anyCtx.restore()
          } else {
            drawAt(x, y, w, h)
          }
        } else {
          drawAt(x, y, w, h)
        }
      }

      finishElement()
    }

    drawRest(0)
      })
  )
}

/**
 * 将模板绘制到 canvas,并导出临时路径供 <image> 展示。
 */
export function renderLabelPreviewToTempPath(
  canvasId: string,
  componentInstance: any,
  template: SystemLabelTemplate,
  maxDisplayWidthPx = 720
): Promise<string> {
  const unit = template.unit || 'inch'
  const cw = Math.max(40, Math.round(toCanvasPx(Number(template.width) || 2, unit)))
  const ch = Math.max(40, Math.round(toCanvasPx(Number(template.height) || 2, unit)))
  const scale = Math.min(1, maxDisplayWidthPx / cw)
  const outW = Math.max(1, Math.round(cw * scale))
  const outH = Math.max(1, Math.round(ch * scale))
  const exportPr = previewExportPixelRatio()

  return runLabelPreviewCanvasDraw(canvasId, componentInstance, template, cw, ch, scale).then(
    () =>
      new Promise<string>((resolve, reject) => {
        setTimeout(() => {
          uni.canvasToTempFilePath(
            {
              canvasId,
              width: outW,
              height: outH,
              destWidth: Math.round(outW * exportPr),
              destHeight: Math.round(outH * exportPr),
              success: (res) => resolve(res.tempFilePath),
              fail: (err) => reject(new Error(err.errMsg || 'canvasToTempFilePath failed')),
            },
            componentInstance
          )
        }, 120)
      })
  )
}

/**
 * 打印专用:与屏幕预览相同走 canvasToTempFilePath(已验证能出图),再由 printImageForCurrentPrinter 用原生 Bitmap 解码光栅化。
 * 避免 canvasGetImageData 在部分机型/页面上下文中返回空或错位,导致 BLE 发出“空标签”仍回调成功。
 */
export function renderLabelPreviewCanvasToTempPathForPrint(
  canvasId: string,
  componentInstance: any,
  template: SystemLabelTemplate,
  layout: { cw: number, ch: number, outW: number, outH: number, scale: number }
): Promise<string> {
  const { cw, ch, outW, outH, scale } = layout
  return runLabelPreviewCanvasDraw(canvasId, componentInstance, template, cw, ch, scale, { forPrint: true }).then(
    () =>
      new Promise<string>((resolve, reject) => {
        setTimeout(() => {
          uni.canvasToTempFilePath(
            {
              canvasId,
              x: 0,
              y: 0,
              width: outW,
              height: outH,
              destWidth: outW,
              destHeight: outH,
              fileType: 'png',
              quality: 1,
              success: (res) => resolve(res.tempFilePath),
              fail: (err) => reject(new Error(err.errMsg || 'canvasToTempFilePath for print failed')),
            },
            componentInstance
          )
        }, 150)
      })
  )
}

function countNonWhiteCanvasPixels (data: ArrayLike<number>, pixelCount: number): number {
  let dark = 0
  for (let i = 0; i < pixelCount; i++) {
    const idx = i * 4
    const red = Number(data[idx] ?? 255)
    const green = Number(data[idx + 1] ?? 255)
    const blue = Number(data[idx + 2] ?? 255)
    const alpha = Number(data[idx + 3] ?? 255)
    if (alpha > 0 && (red < 250 || green < 250 || blue < 250)) dark++
  }
  return dark
}

function captureLabelPreviewCanvasImageData (
  canvasId: string,
  componentInstance: any,
  outW: number,
  outH: number,
  settleMs = 150,
): Promise<RawImageDataSource> {
  return new Promise<RawImageDataSource>((resolve, reject) => {
    setTimeout(() => {
      uni.canvasGetImageData(
        {
          canvasId,
          x: 0,
          y: 0,
          width: outW,
          height: outH,
          success: (res: any) => {
            resolve({
              width: outW,
              height: outH,
              data: res.data,
            })
          },
          fail: (err: any) => {
            reject(new Error(err?.errMsg || 'canvasGetImageData for print failed'))
          },
        },
        componentInstance,
      )
    }, settleMs)
  })
}

/**
 * 与 `shouldRasterPrintViaCanvasImageData()` 配套:内置 UPOS 等机型不走 Bitmap int[],与 Test Print 一致用 canvasGetImageData。
 */
export async function renderLabelPreviewCanvasImageDataForPrint(
  canvasId: string,
  componentInstance: any,
  template: SystemLabelTemplate,
  layout: { cw: number, ch: number, outW: number, outH: number, scale: number }
): Promise<RawImageDataSource> {
  const { cw, ch, outW, outH, scale } = layout
  const pixelCount = Math.max(1, outW * outH)

  const drawAndCapture = async (settleMs: number) => {
    await runLabelPreviewCanvasDraw(canvasId, componentInstance, template, cw, ch, scale, { forPrint: true })
    return captureLabelPreviewCanvasImageData(canvasId, componentInstance, outW, outH, settleMs)
  }

  let imageData = await drawAndCapture(150)
  if (countNonWhiteCanvasPixels(imageData.data, pixelCount) <= 0) {
    await settleAfterLabelCanvasResize()
    imageData = await drawAndCapture(220)
  }
  if (countNonWhiteCanvasPixels(imageData.data, pixelCount) <= 0) {
    throw new Error(`CANVAS_RASTER_EMPTY:size=${outW}x${outH}`)
  }
  return imageData
}

/**
 * 按打印机最大宽度(dots)与 DPI 计算栅格尺寸;宽为 8 的倍数,与 Test Print / rasterizeImageData 一致。
 */
/** 调整 canvas :width/:height 后等待绘图缓冲区就绪,避免光栅导出高度不足导致底部条码/日期被裁切 */
export async function settleAfterLabelCanvasResize (): Promise<void> {
  await new Promise<void>((r) => setTimeout(r, 16))
  await new Promise<void>((resolve) => {
    if (typeof requestAnimationFrame === 'function') {
      requestAnimationFrame(() => requestAnimationFrame(() => resolve()))
    } else {
      setTimeout(() => resolve(), 32)
    }
  })
  await new Promise<void>((r) => setTimeout(r, 80))
}

export function getLabelPrintRasterLayout(
  template: SystemLabelTemplate,
  maxWidthDots: number,
  printDpi = 203,
): { cw: number, ch: number, outW: number, outH: number, scale: number } {
  const { cw, ch } = resolveLabelDesignCanvasPx(template)
  const designDpi = 96
  const idealW = Math.round(cw * (printDpi / designDpi))
  const cap = Math.max(8, Math.round(maxWidthDots || 576))
  let outW = Math.max(8, Math.min(cap, idealW))
  outW -= outW % 8
  if (outW < 8) outW = 8
  const scale = outW / cw
  const outH = Math.max(1, Math.round(ch * scale))
  return { cw, ch, outW, outH, scale }
}

export function getPreviewCanvasCssSize(template: SystemLabelTemplate, maxDisplayWidthPx = 720): {
  width: number
  height: number
} {
  const { cw, ch } = resolveLabelDesignCanvasPx(template)
  const scale = Math.min(1, maxDisplayWidthPx / cw)
  return {
    width: Math.max(1, Math.round(cw * scale)),
    height: Math.max(1, Math.round(ch * scale)),
  }
}