Blame view

美国版/Food Labeling Management App UniApp/src/utils/labelPreview/normalizePreviewTemplate.ts 23.5 KB
143afd59   杨鑫   打印,标签
1
  import type { SystemLabelTemplate, SystemTemplateElementBase } from '../print/types/printer'
540ac0e3   杨鑫   前端修改bug
2
3
  import {
    applyLiveDateTimeFieldsToTemplate,
fdce24a6   杨鑫   修改bug
4
    captureDateDisplayFormatInConfig,
9d218930   杨鑫   修改
5
    isUniAppDateTimeOffsetField,
fdce24a6   杨鑫   修改bug
6
    parseStoredPrintInputOffset,
540ac0e3   杨鑫   前端修改bug
7
    resolveTemplateDefaultValueForElement,
fdce24a6   杨鑫   修改bug
8
    sanitizeDateElementConfig,
9d218930   杨鑫   修改
9
    tryParsePrintInputOffsetStored,
540ac0e3   杨鑫   前端修改bug
10
  } from './printInputOffset'
63289723   杨鑫   提交
11
  import { applyNutritionDefaultJsonToConfig } from './nutritionDefaultsMerge'
143afd59   杨鑫   打印,标签
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
  
  function asRecord(v: unknown): Record<string, unknown> {
    if (v != null && typeof v === 'object' && !Array.isArray(v)) return v as Record<string, unknown>
    return {}
  }
  
  function normalizeConfig(raw: unknown): Record<string, unknown> {
    if (raw == null) return {}
    if (typeof raw === 'string') {
      const t = raw.trim()
      if (!t) return {}
      try {
        const parsed = JSON.parse(t) as unknown
        if (parsed != null && typeof parsed === 'object' && !Array.isArray(parsed)) {
          return { ...(parsed as Record<string, unknown>) }
        }
      } catch {
        return {}
      }
      return {}
    }
    const o = asRecord(raw)
    return { ...o }
  }
  
b04bc3a5   杨鑫   打印日志 重新打印
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
  /**
   * 落库/列表返回的 element 可能把 text、src、fontSize 等摊在根上,仅 `config` 为空或不全;
   * 合并进 config 后打印与预览才能读到样式与图片地址。
   */
  function mergeFlatElementFieldsIntoConfig(
    e: Record<string, unknown>,
    cfg: Record<string, unknown>,
  ): Record<string, unknown> {
    const out = { ...cfg }
    const keys = [
      'text',
      'Text',
      'prefix',
      'Prefix',
      'suffix',
      'Suffix',
      'fontSize',
      'FontSize',
      'textAlign',
      'TextAlign',
20554770   杨鑫   更新bug
57
58
      'verticalAlign',
      'VerticalAlign',
b04bc3a5   杨鑫   打印日志 重新打印
59
      'fontFamily',
20554770   杨鑫   更新bug
60
      'FontFamily',
b04bc3a5   杨鑫   打印日志 重新打印
61
      'fontWeight',
20554770   杨鑫   更新bug
62
63
64
65
66
      'FontWeight',
      'fontStyle',
      'FontStyle',
      'textDecoration',
      'TextDecoration',
b04bc3a5   杨鑫   打印日志 重新打印
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
      'color',
      'Color',
      'src',
      'Src',
      'url',
      'Url',
      'data',
      'Data',
      'value',
      'Value',
      'unit',
      'Unit',
      'format',
      'Format',
      'decimal',
      'Decimal',
      'inputType',
      'InputType',
      'offsetDays',
      'OffsetDays',
      'multipleOptionId',
      'MultipleOptionId',
      'multipleOptionName',
      'MultipleOptionName',
      'selectedOptionValues',
      'SelectedOptionValues',
      'errorLevel',
      'scaleMode',
20554770   杨鑫   更新bug
95
96
      'weightInputMode',
      'WeightInputMode',
b04bc3a5   杨鑫   打印日志 重新打印
97
98
99
      'showText',
      'placeholder',
      'Placeholder',
540ac0e3   杨鑫   前端修改bug
100
101
      'invertColors',
      'InvertColors',
b04bc3a5   杨鑫   打印日志 重新打印
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
    ] as const
    for (const k of keys) {
      const existing = out[k]
      const has =
        existing !== undefined &&
        existing !== null &&
        !(typeof existing === 'string' && String(existing).trim() === '')
      if (has) continue
      const v = e[k]
      if (v !== undefined && v !== null && !(typeof v === 'string' && String(v).trim() === '')) {
        out[k] = v as unknown
      }
    }
    return out
  }
  
143afd59   杨鑫   打印,标签
118
  const TEXT_PRODUCT_PLACEHOLDERS = new Set(['', '文本', 'text', 'Text', 'TEXT', 'Label', 'label'])
fdce24a6   杨鑫   修改bug
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
  const LABEL_NAME_PLACEHOLDERS = new Set([
    ...TEXT_PRODUCT_PLACEHOLDERS,
    'Label Name',
    'label name',
    'labelname',
    'Product name',
    'product name',
  ])
  
  function normalizeLabelPanelTypeAdd(el: SystemTemplateElementBase): string {
    const raw = String(
      (el as { typeAdd?: string }).typeAdd ??
        (el.config as Record<string, unknown>)?.typeAdd ??
        (el.config as Record<string, unknown>)?.TypeAdd ??
        '',
    )
      .trim()
      .toLowerCase()
      .replace(/\s+/g, ' ')
    return raw
  }
  
  /** Label 面板 **Label Name**(typeAdd 如 label_Label Name) */
  export function isTemplateLabelNameElement(el: SystemTemplateElementBase): boolean {
    if (normalizeLabelPanelTypeAdd(el) === 'label_label name') return true
    const en = String(el.elementName ?? '').trim().toLowerCase()
    return en === 'label name' || en === 'labelname'
  }
  
  /** Label 面板 **Label Type**(typeAdd 如 label_Label Type) */
  export function isTemplateLabelTypeElement(el: SystemTemplateElementBase): boolean {
    if (normalizeLabelPanelTypeAdd(el) === 'label_label type') return true
    const en = String(el.elementName ?? '').trim().toLowerCase()
    return en === 'label type' || en === 'labeltype'
  }
  
  /**
   * 将 Label Name / Label Type 绑定写入模板(与 Web mergeLabelBindingsIntoTextValues 对齐)。
   */
  export function applyLabelBindingsToPreviewTemplate(
    template: SystemLabelTemplate,
    bindings: { labelName?: string; labelTypeName?: string; productName?: string },
  ): SystemLabelTemplate {
    const labelName = String(bindings.labelName ?? '').trim()
    const labelTypeName = String(bindings.labelTypeName ?? '').trim()
    const productName = String(bindings.productName ?? '').trim()
    const resolvedLabelName = labelName || productName
    if (!resolvedLabelName && !labelTypeName) return template
  
    const elements = (template.elements || []).map((el) => {
      const type = String(el.type || '').toUpperCase()
      const cfg = { ...(el.config || {}) } as Record<string, unknown>
      const raw = String(cfg.text ?? cfg.Text ?? '').trim()
  
      if (resolvedLabelName && isTemplateLabelNameElement(el)) {
        if (!raw || LABEL_NAME_PLACEHOLDERS.has(raw)) {
          return { ...el, config: { ...cfg, text: resolvedLabelName, Text: resolvedLabelName } }
        }
      }
      if (labelTypeName && isTemplateLabelTypeElement(el)) {
        return { ...el, config: { ...cfg, text: labelTypeName, Text: labelTypeName } }
      }
      if (resolvedLabelName && type === 'TEXT_PRODUCT' && (!raw || TEXT_PRODUCT_PLACEHOLDERS.has(raw))) {
        return { ...el, config: { ...cfg, text: resolvedLabelName, Text: resolvedLabelName } }
      }
      return el
    })
    return { ...template, elements }
  }
143afd59   杨鑫   打印,标签
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
  
  /**
   * Web 端设计器里 TEXT_PRODUCT 若为 FIXED 且占位「文本」,预览页用当前商品名覆盖(与列表传入的 productName 一致)。
   */
  export function overlayProductNameOnPreviewTemplate(
    template: SystemLabelTemplate,
    productName: string | undefined
  ): SystemLabelTemplate {
    const name = (productName ?? '').trim()
    if (!name) return template
    const elements = (template.elements || []).map((el) => {
      const type = String(el.type || '').toUpperCase()
      if (type !== 'TEXT_PRODUCT') return el
      const raw = String((el.config as any)?.text ?? (el.config as any)?.Text ?? '').trim()
      if (raw && !TEXT_PRODUCT_PLACEHOLDERS.has(raw)) return el
      return {
        ...el,
        config: { ...(el.config || {}), text: name },
      }
    })
    return { ...template, elements }
  }
  
  /**
   * 解析接口 `labelSizeText`(如 `2"x2"`、`6.00x4.00cm`、`2.00*2.00"`)。
   * 无单位后缀时默认 **inch**(与历史 `2"x2"` 一致)。
   */
  export function parseLabelSizeText(
    raw: string | null | undefined
  ): { width: number; height: number; unit: 'inch' | 'mm' | 'cm' | 'px' } | null {
    if (raw == null) return null
    let s = String(raw).trim()
    if (!s) return null
    s = s.replace(/["'\u201C\u201D\u2018\u2019\u2032\u2033]/g, '').replace(/\s+/g, '').toLowerCase()
    const m = s.match(/^(\d+(?:\.\d+)?)[*×x](\d+(?:\.\d+)?)(mm|cm|inch|in|px)?$/i)
    if (!m) return null
    const w = Number(m[1])
    const h = Number(m[2])
    if (!Number.isFinite(w) || !Number.isFinite(h) || w <= 0 || h <= 0) return null
    const suf = (m[3] || '').toLowerCase()
    let unit: 'inch' | 'mm' | 'cm' | 'px' = 'inch'
    if (suf === 'mm') unit = 'mm'
    else if (suf === 'cm') unit = 'cm'
    else if (suf === 'px') unit = 'px'
    else if (suf === 'in' || suf === 'inch') unit = 'inch'
    return { width: w, height: h, unit }
  }
  
  /**
   * 用 `labelSizeText` 覆盖模板物理宽高(解析失败则保持原模板)。
   * 注意:App 预览画布应以接口 **template.width / height / unit** 为准(见 preview 页),勿与本函数同时叠加强制覆盖。
   */
  export function applyLabelSizeTextToTemplate(
    template: SystemLabelTemplate,
    labelSizeText: string | null | undefined
  ): SystemLabelTemplate {
    const parsed = parseLabelSizeText(labelSizeText)
    if (!parsed) return template
    return {
      ...template,
      unit: parsed.unit,
      width: parsed.width,
      height: parsed.height,
    }
  }
  
  /**
9d218930   杨鑫   修改
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
   * 将接口/缓存中的默认值统一为字符串(兼容 object、双重 JSON 编码、PascalCase unit/value)。
   */
  export function coerceTemplateProductDefaultValueToString(v: unknown): string {
    if (v == null) return ''
    if (typeof v === 'string') {
      const t = v.trim()
      if (!t) return ''
      if (t.startsWith('{') || t.startsWith('[')) return t
      if (t.startsWith('"') && t.endsWith('"')) {
        try {
          const inner = JSON.parse(t) as unknown
          if (typeof inner === 'string') return inner.trim()
        } catch {
          /* ignore */
        }
      }
      return t
    }
    if (typeof v === 'number' || typeof v === 'boolean') return String(v)
    if (typeof v === 'object' && !Array.isArray(v)) {
      const rec = v as Record<string, unknown>
      const unit = rec.unit ?? rec.Unit
      const value = rec.value ?? rec.Value
      if (unit != null && value != null) {
        return JSON.stringify({ unit: String(unit), value: String(value) })
      }
    }
    try {
      return JSON.stringify(v)
    } catch {
      return String(v)
    }
  }
  
  /**
143afd59   杨鑫   打印,标签
290
291
292
293
294
295
296
297
298
299
   * 从预览接口响应中取出 `templateProductDefaultValues`(elementId → 字符串,兼容 PascalCase / 嵌套 data)。
   */
  export function extractTemplateProductDefaultValuesFromPreviewPayload(payload: unknown): Record<string, string> {
    const tryLayer = (layer: unknown): Record<string, string> | null => {
      if (layer == null || typeof layer !== 'object' || Array.isArray(layer)) return null
      const L = layer as Record<string, unknown>
      const raw = L.templateProductDefaultValues ?? L.TemplateProductDefaultValues
      if (raw == null || typeof raw !== 'object' || Array.isArray(raw)) return null
      const out: Record<string, string> = {}
      for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
3ead62fc   杨鑫   优化
300
301
        const key = String(k).trim()
        if (!key) continue
9d218930   杨鑫   修改
302
        out[key] = coerceTemplateProductDefaultValueToString(v)
3ead62fc   杨鑫   优化
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
      }
      return Object.keys(out).length ? out : null
    }
  
    const unwrapTemplateNode = (raw: unknown): Record<string, unknown> | null => {
      if (raw == null) return null
      if (typeof raw === 'string') {
        const s = raw.trim()
        if (!s) return null
        try {
          const p = JSON.parse(s) as unknown
          if (p != null && typeof p === 'object' && !Array.isArray(p)) return p as Record<string, unknown>
        } catch {
          return null
        }
        return null
      }
      if (typeof raw === 'object' && !Array.isArray(raw)) return raw as Record<string, unknown>
      return null
    }
  
    /** 多来源合并:后者覆盖前者,便于「嵌套在 template 内」与「与 template 平级」同时存在时取全。 */
    const mergeMaps = (...maps: (Record<string, string> | null | undefined)[]): Record<string, string> => {
      const out: Record<string, string> = {}
      for (const m of maps) {
        if (!m) continue
        for (const [k, v] of Object.entries(m)) {
          const key = String(k).trim()
          if (!key) continue
          out[key] = v
        }
143afd59   杨鑫   打印,标签
334
335
336
337
338
339
340
341
342
343
344
345
      }
      return out
    }
  
    if (payload == null || typeof payload !== 'object') return {}
    const r = payload as Record<string, unknown>
    const nested = r.data ?? r.Data
    const inner =
      nested != null && typeof nested === 'object' && !Array.isArray(nested)
        ? (nested as Record<string, unknown>)
        : null
  
3ead62fc   杨鑫   优化
346
347
348
349
350
351
352
353
354
    const innerTpl = inner ? unwrapTemplateNode(inner.template ?? inner.Template) : null
    const rootTpl = unwrapTemplateNode(r.template ?? r.Template)
  
    return mergeMaps(
      innerTpl ? tryLayer(innerTpl) : null,
      rootTpl ? tryLayer(rootTpl) : null,
      inner ? tryLayer(inner) : null,
      tryLayer(r),
      tryLayer(payload),
9d218930   杨鑫   修改
355
356
      tryExtractFromTemplateProductDefaultsArray(r),
      inner ? tryExtractFromTemplateProductDefaultsArray(inner) : null,
3ead62fc   杨鑫   优化
357
    )
143afd59   杨鑫   打印,标签
358
359
  }
  
9d218930   杨鑫   修改
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
  /** Web 模板 DTO 的 templateProductDefaults 数组 → 扁平 elementId → value */
  function tryExtractFromTemplateProductDefaultsArray(layer: unknown): Record<string, string> | null {
    if (layer == null || typeof layer !== 'object' || Array.isArray(layer)) return null
    const L = layer as Record<string, unknown>
    const raw = L.templateProductDefaults ?? L.TemplateProductDefaults
    if (!Array.isArray(raw)) return null
    const out: Record<string, string> = {}
    for (const row of raw) {
      if (row == null || typeof row !== 'object' || Array.isArray(row)) continue
      const rec = row as Record<string, unknown>
      const dv = rec.defaultValues ?? rec.DefaultValues
      if (dv == null || typeof dv !== 'object' || Array.isArray(dv)) continue
      for (const [k, v] of Object.entries(dv as Record<string, unknown>)) {
        const key = String(k).trim()
        if (!key) continue
        out[key] = coerceTemplateProductDefaultValueToString(v)
      }
    }
    return Object.keys(out).length ? out : null
  }
  
923d50c0   杨鑫   更新bug
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
  function isTemplateSectionScanElement(el: SystemTemplateElementBase): boolean {
    const cfg = el.config || {}
    const typeAdd = String(
      (el as { typeAdd?: string }).typeAdd ??
      cfg.typeAdd ??
      cfg.TypeAdd ??
      el.type ??
      '',
    )
      .trim()
      .toLowerCase()
    if (!typeAdd.startsWith('template_')) return false
    const t = String(el.type || '').toUpperCase()
    return t === 'BARCODE' || t === 'QRCODE'
  }
  
  /** 预览/打印接口响应中的产品 codeValue(兼容 PascalCase / data 嵌套) */
  export function extractProductCodeValueFromPreviewPayload(payload: unknown): string {
    const readLayer = (layer: Record<string, unknown> | null | undefined): string => {
      if (!layer) return ''
      const cv =
        layer.codeValue ??
        layer.CodeValue ??
        layer.productCodeValue ??
        layer.ProductCodeValue
      if (cv != null && String(cv).trim()) return String(cv).trim()
      const prod = layer.product ?? layer.Product
      if (prod != null && typeof prod === 'object' && !Array.isArray(prod)) {
        const p = prod as Record<string, unknown>
        const nested = p.codeValue ?? p.CodeValue
        if (nested != null && String(nested).trim()) return String(nested).trim()
      }
      return ''
    }
    if (payload == null || typeof payload !== 'object') return ''
    const r = payload as Record<string, unknown>
    const nested = r.data ?? r.Data
    const inner =
      nested != null && typeof nested === 'object' && !Array.isArray(nested)
        ? (nested as Record<string, unknown>)
        : null
    return (
      readLayer(inner) ||
      readLayer(r) ||
      ''
    )
  }
  
  /** 将产品 codeValue 写入 Template 分组下的 BARCODE / QRCODE(覆盖模板内静态 data) */
  export function applyProductCodeValueToTemplateScanElements(
    template: SystemLabelTemplate,
    codeValue: string | null | undefined,
  ): SystemLabelTemplate {
    const cv = String(codeValue ?? '').trim()
    if (!cv) return template
    const elements = (template.elements || []).map((el) => {
      if (!isTemplateSectionScanElement(el)) return el
      const cfg = { ...(el.config || {}) } as Record<string, unknown>
      cfg.data = cv
      cfg.Data = cv
      if (String(el.type || '').toUpperCase() === 'BARCODE') {
        cfg.barcodeData = cv
        cfg.BarcodeData = cv
        cfg.value = cv
        cfg.Value = cv
        cfg.content = cv
        cfg.Content = cv
      }
      return { ...el, config: cfg }
    })
    return { ...template, elements }
  }
  
143afd59   杨鑫   打印,标签
454
  /**
9d218930   杨鑫   修改
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
   * 从 templateProductDefaultValues 按 id / inputKey / elementName 匹配(大小写不敏感兜底)。
   */
  export function lookupTemplateProductDefaultValue(
    el: SystemTemplateElementBase,
    defaults: Record<string, string>,
  ): string | undefined {
    const candidates = [
      String(el.id ?? '').trim(),
      String(el.inputKey ?? '').trim(),
      String(el.elementName ?? '').trim(),
    ].filter(Boolean)
    for (const k of candidates) {
      if (Object.prototype.hasOwnProperty.call(defaults, k)) return defaults[k]
    }
    const lowerEntries = Object.entries(defaults).map(([k, v]) => [k.toLowerCase(), v] as const)
    for (const k of candidates) {
      const lk = k.toLowerCase()
      const hit = lowerEntries.find(([dk]) => dk === lk)
      if (hit) return hit[1]
    }
    return undefined
  }
  
  /**
143afd59   杨鑫   打印,标签
479
480
481
482
   * 将平台录入的默认值合并进模板元素 config,供画布预览(键与 elements[].id 一致)。
   */
  export function applyTemplateProductDefaultValuesToTemplate(
    template: SystemLabelTemplate,
540ac0e3   杨鑫   前端修改bug
483
484
    defaults: Record<string, string>,
    base: Date = new Date(),
143afd59   杨鑫   打印,标签
485
486
487
488
  ): SystemLabelTemplate {
    const keys = Object.keys(defaults)
    if (!keys.length) return template
    const elements = (template.elements || []).map((el) => {
9d218930   杨鑫   修改
489
      const v = lookupTemplateProductDefaultValue(el, defaults)
143afd59   杨鑫   打印,标签
490
491
492
493
494
495
496
497
498
499
500
501
502
503
      if (v === undefined) return el
      const type = String(el.type || '').toUpperCase()
      const cfg = { ...(el.config || {}) } as Record<string, any>
  
      if (type === 'IMAGE' || type === 'LOGO') {
        cfg.src = v
        cfg.url = v
        cfg.Src = v
        cfg.Url = v
        return { ...el, config: cfg }
      }
      if (type === 'BARCODE' || type === 'QRCODE') {
        cfg.data = v
        cfg.Data = v
3ead62fc   杨鑫   优化
504
505
506
507
508
509
510
511
        if (type === 'BARCODE') {
          cfg.barcodeData = v
          cfg.BarcodeData = v
          cfg.value = v
          cfg.Value = v
          cfg.content = v
          cfg.Content = v
        }
143afd59   杨鑫   打印,标签
512
513
514
515
516
517
518
519
520
521
        return { ...el, config: cfg }
      }
      if (type === 'WEIGHT') {
        cfg.value = v
        cfg.Value = v
        cfg.text = v
        cfg.Text = v
        return { ...el, config: cfg }
      }
  
699ea6e8   杨鑫   完善打印逻辑
522
      if (type === 'DATE' || type === 'TIME' || type === 'DURATION') {
fdce24a6   杨鑫   修改bug
523
524
525
526
527
528
529
530
531
532
        captureDateDisplayFormatInConfig(cfg)
        sanitizeDateElementConfig(el, cfg)
        /** 偏移类字段只保留 JSON / 纯数字,展示由 applyLiveDateTimeFieldsToTemplate 按 format 重算 */
        if (isUniAppDateTimeOffsetField(el)) {
          const trimmed = String(v).trim()
          if (parseStoredPrintInputOffset(trimmed) || /^\d+$/.test(trimmed)) {
            cfg.text = trimmed
            cfg.Text = trimmed
          }
          return { ...el, config: cfg }
9d218930   杨鑫   修改
533
        }
fdce24a6   杨鑫   修改bug
534
535
536
        const text = resolveTemplateDefaultValueForElement(el, v, base)
        cfg.text = text
        cfg.Text = text
699ea6e8   杨鑫   完善打印逻辑
537
538
539
        return { ...el, config: cfg }
      }
  
63289723   杨鑫   提交
540
541
542
543
544
545
546
547
548
549
550
      if (type === 'NUTRITION') {
        const s = String(v).trim()
        if (s.startsWith('{')) {
          const merged = applyNutritionDefaultJsonToConfig(cfg, s)
          return { ...el, config: merged }
        }
        cfg.text = s
        cfg.Text = s
        return { ...el, config: cfg }
      }
  
143afd59   杨鑫   打印,标签
551
552
553
554
      cfg.text = v
      cfg.Text = v
      return { ...el, config: cfg }
    })
540ac0e3   杨鑫   前端修改bug
555
    return applyLiveDateTimeFieldsToTemplate({ ...template, elements }, base)
143afd59   杨鑫   打印,标签
556
557
  }
  
b04bc3a5   杨鑫   打印日志 重新打印
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
  function elementArrayLength (o: Record<string, unknown>): number {
    const a = o.elements ?? o.Elements
    return Array.isArray(a) ? a.length : 0
  }
  
  /**
   * 列表 `renderTemplateJson` / 接口 9 落库可能是:① 根上直接 elements;② 包在 `printInputJson`;③ 包在 `template`(对象或 JSON 字符串);
   * ④ 根上既有 `template: {}` 又有 `elements` 时,**不能**误用空 template 丢掉根级 elements(会导致重打无字、无图)。
   */
  function pickTemplateRootRecord (payload: Record<string, unknown>): Record<string, unknown> {
    const unwrapTemplateKey = (raw: unknown): Record<string, unknown> | null => {
      if (raw == null) return null
      if (typeof raw === 'string') {
        const s = raw.trim()
        if (!s) return null
        try {
          const p = JSON.parse(s) as unknown
          if (p != null && typeof p === 'object' && !Array.isArray(p)) return p as Record<string, unknown>
        } catch {
          return null
        }
        return null
      }
      if (typeof raw === 'object' && !Array.isArray(raw)) return raw as Record<string, unknown>
      return null
    }
  
    if (elementArrayLength(payload) > 0) return payload
  
    const pi = payload.printInputJson ?? payload.PrintInputJson
    if (pi != null && typeof pi === 'object' && !Array.isArray(pi)) {
      const p = pi as Record<string, unknown>
      if (elementArrayLength(p) > 0) return p
    }
  
    const nested =
      unwrapTemplateKey(payload.template ?? payload.Template) ?? asRecord(payload.template ?? payload.Template)
    if (elementArrayLength(nested) > 0) return nested
  
    if (pi != null && typeof pi === 'object' && !Array.isArray(pi)) return pi as Record<string, unknown>
    if (Object.keys(nested).length > 0) return nested
    return payload
  }
  
b11f42ef   杨鑫   修改
602
603
604
605
606
  export function normalizeTemplatePrintOrientation(raw: unknown): 'horizontal' | 'vertical' {
    const v = String(raw ?? '').trim().toLowerCase()
    return v === 'horizontal' ? 'horizontal' : 'vertical'
  }
  
143afd59   杨鑫   打印,标签
607
608
609
610
611
  /**
   * 将接口 8.2 返回的 template(或整段 DTO)规范为 SystemLabelTemplate,供打印适配器与预览画布使用。
   */
  export function normalizeLabelTemplateFromPreviewApi(payload: unknown): SystemLabelTemplate | null {
    if (payload == null || typeof payload !== 'object') return null
b04bc3a5   杨鑫   打印日志 重新打印
612
613
614
615
616
617
    let root = payload as Record<string, unknown>
    const wrapped = root.data ?? root.Data
    if (wrapped != null && typeof wrapped === 'object' && !Array.isArray(wrapped)) {
      root = wrapped as Record<string, unknown>
    }
    const t = pickTemplateRootRecord(root)
143afd59   杨鑫   打印,标签
618
619
620
621
622
    const elementsRaw = t.elements ?? t.Elements
    if (!Array.isArray(elementsRaw)) return null
  
    const elements: SystemTemplateElementBase[] = (elementsRaw as unknown[]).map((el, index) => {
      const e = asRecord(el)
b04bc3a5   杨鑫   打印日志 重新打印
623
624
625
626
      let cfg = normalizeConfig(
        e.config ?? e.Config ?? e.ConfigJson ?? e.configJson ?? e.ConfigString,
      )
      cfg = mergeFlatElementFieldsIntoConfig(e, cfg)
fdce24a6   杨鑫   修改bug
627
      captureDateDisplayFormatInConfig(cfg)
143afd59   杨鑫   打印,标签
628
629
630
631
      const type = String(e.type ?? e.elementType ?? e.ElementType ?? 'TEXT_STATIC')
      const vst = e.valueSourceType ?? e.ValueSourceType
      const ik = e.inputKey ?? e.InputKey
      const en = e.elementName ?? e.ElementName
540ac0e3   杨鑫   前端修改bug
632
633
      const typeAddRaw = e.typeAdd ?? e.TypeAdd
      const baseEl = {
143afd59   杨鑫   打印,标签
634
635
636
637
638
639
640
        id: String(e.id ?? e.Id ?? `el-${index}`),
        type,
        x: Number(e.x ?? e.posX ?? e.PosX ?? 0),
        y: Number(e.y ?? e.posY ?? e.PosY ?? 0),
        width: Number(e.width ?? e.Width ?? 0),
        height: Number(e.height ?? e.Height ?? 0),
        rotation: String(e.rotation ?? e.Rotation ?? 'horizontal') as 'horizontal' | 'vertical',
20554770   杨鑫   更新bug
641
        border: String(e.border ?? e.Border ?? e.BorderType ?? e.borderType ?? 'none'),
143afd59   杨鑫   打印,标签
642
643
644
645
646
647
        config: cfg as Record<string, any>,
        zIndex: Number(e.zIndex ?? e.ZIndex ?? 0),
        orderNum: Number(e.orderNum ?? e.OrderNum ?? index),
        valueSourceType: vst != null ? String(vst) : undefined,
        inputKey: ik != null && String(ik).trim() !== '' ? String(ik).trim() : undefined,
        elementName: en != null && String(en).trim() !== '' ? String(en).trim() : undefined,
540ac0e3   杨鑫   前端修改bug
648
649
650
651
      } as SystemTemplateElementBase & { zIndex: number; orderNum: number; typeAdd?: string }
      if (typeAddRaw != null && String(typeAddRaw).trim() !== '') {
        baseEl.typeAdd = String(typeAddRaw).trim()
      }
fdce24a6   杨鑫   修改bug
652
      sanitizeDateElementConfig(baseEl, cfg as Record<string, unknown>)
540ac0e3   杨鑫   前端修改bug
653
      return baseEl
143afd59   杨鑫   打印,标签
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
    })
  
    const unitRaw = String(t.unit ?? t.Unit ?? 'inch').toLowerCase()
    const unit = (unitRaw === 'mm' || unitRaw === 'cm' || unitRaw === 'px' ? unitRaw : 'inch') as
      | 'inch'
      | 'mm'
      | 'cm'
      | 'px'
  
    return {
      id: String(t.id ?? t.Id ?? 'preview'),
      name: String(t.name ?? t.Name ?? 'Label'),
      labelType: String(t.labelType ?? t.LabelType ?? ''),
      unit,
      width: Number(t.width ?? t.Width ?? 2),
      height: Number(t.height ?? t.Height ?? 2),
      appliedLocation: String(t.appliedLocation ?? t.AppliedLocation ?? 'ALL'),
      showRuler: !!(t.showRuler ?? t.ShowRuler),
      showGrid: !!(t.showGrid ?? t.ShowGrid),
540ac0e3   杨鑫   前端修改bug
673
      border: String(t.border ?? t.Border ?? t.BorderType ?? t.borderType ?? 'none'),
b11f42ef   杨鑫   修改
674
675
676
      printOrientation: normalizeTemplatePrintOrientation(
        t.printOrientation ?? t.PrintOrientation,
      ),
143afd59   杨鑫   打印,标签
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
      elements,
    }
  }
  
  export function sortElementsForPreview(
    elements: SystemTemplateElementBase[]
  ): SystemTemplateElementBase[] {
    return [...elements].sort((a, b) => {
      const za = Number((a as any).zIndex ?? 0)
      const zb = Number((b as any).zIndex ?? 0)
      if (za !== zb) return za - zb
      const oa = Number((a as any).orderNum ?? 0)
      const ob = Number((b as any).orderNum ?? 0)
      return oa - ob
    })
  }