preview.vue
92.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
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
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
<template>
<view class="page">
<view class="header-hero" :style="{ paddingTop: statusBarHeight + 'px' }">
<view class="top-bar">
<view class="top-left" @click="goBack">
<AppIcon name="chevronLeft" size="sm" color="white" />
</view>
<view class="top-center">
<text class="page-title">Label Preview</text>
<LocationPicker />
</view>
<view class="top-right" @click="isMenuOpen = true">
<AppIcon name="menu" size="sm" color="white" />
</view>
</view>
</view>
<view class="content">
<view v-if="previewLoading" class="state-block">
<text class="state-text">Loading preview…</text>
</view>
<view v-else-if="previewError" class="state-block">
<text class="state-text">{{ previewError }}</text>
</view>
<template v-else>
<view class="food-card">
<view class="food-info">
<text class="food-name">{{ displayProductName }}</text>
<text class="food-cat">{{ productCategory }}</text>
<view v-if="labelTypeName" class="food-label-type">
<AppIcon name="tag" size="sm" color="primary" />
<text class="food-label-type-text">{{ labelTypeName }}</text>
</view>
</view>
<view class="food-template">
<text class="template-size">{{ templateSize }}</text>
<text class="template-name">{{ templateName }}</text>
</view>
</view>
<view class="qty-card">
<text class="qty-label">Print Quantity</text>
<view class="qty-control">
<view class="qty-btn" :class="{ disabled: printQty <= 1 }" @click="decrement">
<AppIcon name="minus" size="sm" color="gray" />
</view>
<text class="qty-value">{{ printQty }}</text>
<view class="qty-btn" @click="increment">
<AppIcon name="plus" size="sm" color="gray" />
</view>
</view>
</view>
<view v-if="printOptionFieldList.length" class="print-options-card">
<text class="print-options-title">Print choices</text>
<text class="print-options-hint">
Choose options for each field. Preview updates to show the selected text (no picker on the label).
</text>
<view v-for="el in printOptionFieldList" :key="el.id" class="print-option-block">
<text class="print-option-label">{{ optionFieldTitle(el) }}</text>
<view class="chip-row">
<view
v-for="opt in dictValuesForElement(el.id)"
:key="el.id + '-' + opt"
class="chip"
:class="{ 'chip-on': isOptionPicked(el.id, opt) }"
@click="togglePrintOption(el.id, opt)"
>
<text class="chip-text">{{ opt }}</text>
</view>
</view>
</view>
</view>
<view v-if="printFreeFieldList.length" class="print-options-card">
<text class="print-options-title">Print input</text>
<text class="print-options-hint">
with a box below. If the template has a unit, it is appended on the label after what you type.
</text>
<view v-for="el in printFreeFieldList" :key="'free-' + el.id" class="print-option-block">
<text class="print-option-label">{{ freeFieldNameLabel(el) }}</text>
<template v-if="freeFieldInputKind(el) === 'text'">
<input
class="free-field-input"
type="text"
:value="printFreeFieldValues[el.id] ?? ''"
:placeholder="freeFieldPlaceholder(el)"
@input="onFreeFieldInput(el.id, $event)"
/>
</template>
<template v-else-if="freeFieldInputKind(el) === 'datetime'">
<view
class="free-field-input picker-input"
@click="openFreeFieldPicker(el, 'datetime')"
>
{{ displayDateTimeField(printFreeFieldValues[el.id], freeFieldDateFormat(el)) }}
</view>
</template>
<template v-else-if="freeFieldInputKind(el) === 'date'">
<view
class="free-field-input picker-input"
@click="openFreeFieldPicker(el, 'date')"
>
{{ displayDateValue(printFreeFieldValues[el.id], freeFieldDateFormat(el), freeFieldPlaceholder(el)) }}
</view>
</template>
<template v-else>
<view
class="free-field-input picker-input"
@click="openFreeFieldPicker(el, 'time')"
>
{{ displayTimeValue(printFreeFieldValues[el.id]) }}
</view>
</template>
</view>
</view>
<text class="section-title">Label Preview</text>
<view class="label-card">
<view class="label-img-wrap">
<image v-if="previewImageSrc" :src="previewImageSrc" class="label-img" mode="widthFix" />
<view v-else class="label-placeholder">
<text class="label-placeholder-text">No preview image</text>
</view>
</view>
</view>
<view class="info-row">
<view class="info-item">
<text class="info-label">Label ID</text>
<text class="info-value">{{ labelIdDisplay }}</text>
</view>
<view class="info-item">
<text class="info-label">Last Edited</text>
<text class="info-value">{{ lastEdited }}</text>
</view>
<view class="info-item">
<text class="info-label">Location</text>
<text class="info-value">{{ locationName }}</text>
</view>
</view>
<view class="note-card">
<AppIcon name="alert" size="sm" color="blue" />
<text class="note-text">This is a preview of the label. Actual printed labels may vary slightly in appearance.</text>
</view>
</template>
</view>
<view class="bottom-bar">
<view class="bottom-info">
<text class="bottom-qty">{{ printQty }} label{{ printQty > 1 ? 's' : '' }}</text>
<view class="bt-indicator" :class="{ connected: btConnected }">
<text class="bt-dot" />
<text class="bt-name">{{ btConnected ? btDeviceName : 'No printer' }}</text>
</view>
</view>
<view class="bottom-actions">
<view class="btn-preview-sq" @click="showPreviewModal = true">
<AppIcon name="eye" size="md" color="primary" />
</view>
<view class="print-btn" :class="{ disabled: isPrinting || previewLoading || !systemTemplate }" @click="handlePrint">
<AppIcon name="printer" size="sm" color="white" />
<text class="print-btn-text">{{ isPrinting ? 'Printing...' : 'Print' }}</text>
</view>
</view>
</view>
<view v-if="showPreviewModal && previewImageSrc" class="modal-mask" @click="showPreviewModal = false">
<view class="modal-body modal-body-label-only" @click.stop>
<view class="modal-label-wrap">
<view class="modal-label-inner">
<image :src="previewImageSrc" class="modal-label-img" mode="widthFix" />
</view>
<view class="modal-label-id">
<text class="modal-label-id-label">Label ID</text>
<text class="modal-label-id-value">{{ labelIdDisplay }}</text>
</view>
</view>
</view>
</view>
<!-- 与 printers 页 Test Print 一致:必须绑定 :width/:height 作为绘图缓冲区像素,否则 canvasGetImageData 多为空白/默认尺寸,打印不出纸 -->
<canvas
canvas-id="labelPreviewCanvas"
id="labelPreviewCanvas"
class="hidden-canvas"
:style="{ width: canvasCssW + 'px', height: canvasCssH + 'px' }"
:width="canvasCssW"
:height="canvasCssH"
/>
<NoPrinterModal v-model="showNoPrinterModal" @connect="goBluetoothPage" />
<SideMenu v-model="isMenuOpen" />
<view v-if="pickerDialogVisible" class="picker-dialog-mask" @click="closeFreeFieldPicker">
<view class="picker-dialog" :class="{ 'picker-dialog--wide': pickerMode === 'datetime' }" @click.stop>
<view class="picker-dialog-title">{{ pickerDialogTitle }}</view>
<picker-view
class="picker-view-box"
:class="{ 'picker-view-box--wide': pickerMode === 'datetime' }"
:indicator-style="pickerIndicatorStyle"
:value="pickerSelection"
@change="onPickerViewChange"
>
<picker-view-column v-if="pickerMode === 'date' || pickerMode === 'datetime'">
<view v-for="y in pickerYears" :key="'y-' + y" class="picker-item">{{ y }}</view>
</picker-view-column>
<picker-view-column v-if="pickerMode === 'date' || pickerMode === 'datetime'">
<view v-for="m in pickerMonths" :key="'m-' + m" class="picker-item">{{ m }}</view>
</picker-view-column>
<picker-view-column v-if="pickerMode === 'date' || pickerMode === 'datetime'">
<view v-for="d in pickerDays" :key="'d-' + d" class="picker-item">{{ d }}</view>
</picker-view-column>
<picker-view-column v-if="pickerMode === 'time' || pickerMode === 'datetime'">
<view v-for="h in pickerHours" :key="'h-' + h" class="picker-item">{{ h }}</view>
</picker-view-column>
<picker-view-column v-if="pickerMode === 'time' || pickerMode === 'datetime'">
<view v-for="m in pickerMinutes" :key="'mm-' + m" class="picker-item">{{ m }}</view>
</picker-view-column>
</picker-view>
<view class="picker-dialog-actions">
<view class="picker-btn picker-btn-cancel" @click="closeFreeFieldPicker">Cancel</view>
<view class="picker-btn picker-btn-confirm" @click="confirmFreeFieldPicker">Confirm</view>
</view>
</view>
</view>
</view>
</template>
<script setup lang="ts">
import { ref, computed, getCurrentInstance, nextTick } from 'vue'
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
import AppIcon from '../../components/AppIcon.vue'
import SideMenu from '../../components/SideMenu.vue'
import LocationPicker from '../../components/LocationPicker.vue'
import NoPrinterModal from '../../components/NoPrinterModal.vue'
import { getStatusBarHeight } from '../../utils/statusBar'
import {
canPrintCurrentLabelViaNativeFastJob,
getCurrentPrinterSummary,
getCurrentPrinterDriver,
getLastImagePrintDebug,
printImageDataForCurrentPrinter,
printImageForCurrentPrinter,
printLabelPrintJobPayloadForCurrentPrinter,
printSystemTemplateForCurrentPrinter,
resolveRasterPrintDriver,
shouldRasterPrintViaCanvasImageData,
} from '../../utils/print/manager/printerManager'
import classicBluetooth from '../../utils/print/bluetoothTool.js'
import { getNativeFastPrinterState, isNativeFastPrinterAvailable } from '../../utils/print/nativeFastPrinter'
import { showNativeFastPrinterDebugModal } from '../../utils/print/showNativeFastPrinterDebugModal'
import type { SystemLabelTemplate, SystemTemplateElementBase } from '../../utils/print/types/printer'
import { fetchLabelMultipleOptionById } from '../../services/labelMultipleOption'
import {
buildPrintInputJson,
ensureFreeFieldKeys,
isPrintInputFreeFieldElement,
isPrintInputOptionsElement,
mergePrintInputFreeFields,
mergePrintOptionSelections,
readFreeFieldValuesFromTemplate,
readSelectionsFromTemplate,
validatePrintInputFreeFieldsBeforePrint,
validatePrintInputOptionsBeforePrint,
} from '../../utils/labelPreview/printInputOptions'
import {
buildLabelPrintJobPayload,
setLastLabelPrintJobPayload,
} from '../../utils/labelPreview/buildLabelPrintPayload'
import { getCurrentStoreId } from '../../utils/stores'
import {
buildApiUrl,
} from '../../utils/apiBase'
import { storedValueLooksLikeImagePath } from '../../utils/resolveMediaUrl'
import {
buildUsAppLabelPrintRequestBody,
postUsAppLabelPreview,
postUsAppLabelPrint,
US_APP_LABEL_PRINT_PATH,
} from '../../services/usAppLabeling'
import {
applyTemplateProductDefaultValuesToTemplate,
applyProductCodeValueToTemplateScanElements,
extractProductCodeValueFromPreviewPayload,
extractTemplateProductDefaultValuesFromPreviewPayload,
normalizeLabelTemplateFromPreviewApi,
overlayProductNameOnPreviewTemplate,
} from '../../utils/labelPreview/normalizePreviewTemplate'
import {
getLabelPrintRasterLayout,
getPreviewCanvasCssSize,
renderLabelPreviewCanvasImageDataForPrint,
renderLabelPreviewCanvasToTempPathForPrint,
renderLabelPreviewToTempPath,
} from '../../utils/labelPreview/renderLabelPreviewCanvas'
import {
hydrateSystemTemplateImagesForPrint,
resetHydrateImageDebugRecords,
} from '../../utils/print/hydrateTemplateImagesForPrint'
import {
normalizeTemplateForNativeFastJob,
templateHasUnsupportedNativeFastElements,
} from '../../utils/print/nativeTemplateElementSupport'
import {
ensureTemplateHeightCoversElements,
getTemplatePhysicalSizeMm,
isTemplateWithinNativeFastPrintBounds,
templateContentHeightPx,
} from '../../utils/print/templatePhysicalMm'
import { isPrinterReadySync } from '../../utils/print/printerReadiness'
import {
ensureNativeClassicTransportIfPossible,
getBluetoothConnection,
isNativeBaseClassicBluetoothTransport,
getPrinterDebugSnapshot,
} from '../../utils/print/printerConnection'
import { isUsAppSessionExpiredError } from '../../utils/usAppApiRequest'
import { getDeviceFingerprint } from '../../utils/deviceInfo'
const statusBarHeight = getStatusBarHeight()
const instance = getCurrentInstance()?.proxy ?? null
const isPrinting = ref(false)
const isMenuOpen = ref(false)
const printQty = ref(1)
const showPreviewModal = ref(false)
const showNoPrinterModal = ref(false)
const btConnected = ref(false)
const btDeviceName = ref('')
/** 业务关闭:预览页不再有打印前/打印后调试弹窗 */
const ENABLE_PRINT_PREFLIGHT_MODAL = false
const ENABLE_PRINT_RESULT_MODAL = false
const ENABLE_AUTO_NATIVE_DEBUG_MODAL = false
function showPrintInProgressDebugModal(meta?: {
jobId?: number
route?: string
stage?: string
}) {
if (!ENABLE_PRINT_RESULT_MODAL) return
try {
uni.showModal({
title: 'Print debug (in progress)',
content: [
`jobId: ${String(meta?.jobId ?? '-')}`,
`route: ${String(meta?.route || '-')}`,
`stage: ${String(meta?.stage || '-')}`,
'',
'Printing is still running. Please take a screenshot.',
].join('\n'),
showCancel: false,
confirmText: 'OK',
})
} catch (_) {}
}
function buildPrintDebugText(extra?: Record<string, string | number | boolean | null | undefined>): string {
const summary = getCurrentPrinterSummary()
const conn = getBluetoothConnection()
const classicState = typeof classicBluetooth?.getDebugState === 'function'
? classicBluetooth.getDebugState()
: null
const native = getNativeFastPrinterState() || {}
const lines: string[] = [
`mode=${summary.type || '-'}`,
`driver=${summary.driverKey || '-'}/${summary.driverName || '-'}`,
`protocol=${summary.protocol || '-'}`,
`deviceType=${summary.deviceType || '-'}`,
conn?.deviceId ? `device=${conn.deviceId}` : '',
conn?.deviceName ? `deviceName=${conn.deviceName}` : '',
(conn as any)?.transportMode ? `transport=${String((conn as any).transportMode)}` : '',
native?.available === false ? `nativeFast=${native.lastError || 'unavailable'}` : '',
].filter(Boolean)
if (classicState) {
lines.push(`classicState=${classicState.connectionState || '-'}`)
lines.push(`connected=${String(!!classicState.socketConnected)}`)
lines.push(`outputReady=${String(!!classicState.outputReady)}`)
lines.push(`sendMode=${classicState.lastSendMode || '-'}`)
if (classicState.lastSocketStrategy) lines.push(`socket=${classicState.lastSocketStrategy}`)
if (classicState.lastSendError) lines.push(`sendError=${classicState.lastSendError}`)
if (classicState.lastSendError || classicState.lastError) {
lines.push(`lastError=${classicState.lastSendError || classicState.lastError}`)
}
}
if (extra) {
Object.keys(extra).forEach((k) => {
const v = (extra as any)[k]
if (v === undefined || v === null || v === '') return
lines.push(`${k}=${String(v)}`)
})
}
return lines.join('\n')
}
function shouldShowNativeFastDebugModal (): boolean {
const summary = getCurrentPrinterSummary()
return summary.type === 'builtin'
|| (summary.type === 'bluetooth' && isNativeBaseClassicBluetoothTransport())
}
function buildPrintPreflightDeviceInfoText (args: {
template: SystemLabelTemplate
useNativeTemplatePrint: boolean
nativeUnsupported: boolean
printerSnapshot?: any
}): string {
const summary = getCurrentPrinterSummary()
const conn = getBluetoothConnection()
const driver = getCurrentPrinterDriver()
const native = getNativeFastPrinterState() || {}
const snap = args.printerSnapshot || null
let sys: any = {}
try { sys = uni.getSystemInfoSync?.() || {} } catch { sys = {} }
const lines: string[] = []
lines.push('Device / System')
lines.push(`- model: ${String(sys.model || '-')}`)
lines.push(`- brand: ${String(sys.brand || '-')}`)
lines.push(`- platform: ${String(sys.platform || '-')}`)
lines.push(`- system: ${String(sys.system || '-')}`)
lines.push(`- fingerprint: ${String(getDeviceFingerprint?.() || '-')}`)
lines.push(`- jsBuild: upos-no-silent-fallback@2026-04-22`)
lines.push('')
lines.push('Printer / Connection')
lines.push(`- selectedType: ${String(summary.type || '-')}`)
lines.push(`- displayName: ${String(summary.displayName || '-')}`)
lines.push(`- driver: ${String(driver?.displayName || driver?.key || '-')}`)
if (snap && typeof snap.builtinTscUserAcknowledged === 'boolean') {
lines.push(`- builtinTscUserAcknowledged: ${snap.builtinTscUserAcknowledged ? 'YES' : 'NO'}`)
}
if (summary.type === 'bluetooth') {
lines.push(`- btDeviceType: ${String(conn?.deviceType || '-')}`)
lines.push(`- btTransportMode: ${String((conn as any)?.transportMode || '-')}`)
lines.push(`- btDeviceName: ${String(conn?.deviceName || '-')}`)
lines.push(`- btDeviceId: ${String(conn?.deviceId || '-')}`)
}
lines.push('')
lines.push('Native-fast-printer')
lines.push(`- available: ${String(!!isNativeFastPrinterAvailable())}`)
if ((native as any).backend) lines.push(`- backend: ${String((native as any).backend)}`)
if ((native as any).pluginVersion) lines.push(`- pluginVersion: ${String((native as any).pluginVersion)}`)
if ((native as any).stage) lines.push(`- stage: ${String((native as any).stage)}`)
if ((native as any).lastError) lines.push(`- lastError: ${String((native as any).lastError)}`)
if (snap) {
lines.push('')
lines.push('Built-in route (detected)')
lines.push(`- uposSupported: ${snap.builtin?.uposSupported ? 'YES' : 'NO'}`)
lines.push(`- uposWillTry: ${snap.builtin?.uposWillTry ? 'YES' : 'NO'}`)
if (snap.builtin?.uposOptions) {
lines.push(`- uposPrefer: ${String(snap.builtin.uposOptions.prefer || '-')}`)
lines.push(`- uposSerialPath: ${String(snap.builtin.uposOptions.serialPath || '-')}`)
lines.push(`- uposBaudrate: ${String(snap.builtin.uposOptions.baudrate || '-')}`)
lines.push(`- uposForce: ${snap.builtin.uposOptions.force ? 'YES' : 'NO'}`)
}
lines.push(`- tcpPluginAvailable: ${snap.builtin?.tcpPluginAvailable ? 'YES' : 'NO'}`)
lines.push(`- savedPort: ${String(snap.builtin?.savedPort || '-')}`)
}
lines.push('')
lines.push('Print route (this job)')
lines.push(`- nativePrintTemplate: ${args.useNativeTemplatePrint ? 'YES' : 'NO'}`)
lines.push(`- nativeBoundsOk: ${String(!!isTemplateWithinNativeFastPrintBounds(args.template))}`)
lines.push(`- nativeUnsupportedElements: ${args.nativeUnsupported ? 'YES' : 'NO'}`)
lines.push('')
lines.push('Note')
lines.push('- Built-in may use UPOS (on-device/serial) or localhost (127.0.0.1). If the app reports success but nothing prints, check uposWillTry / tcpPluginAvailable and native-fast-printer lastError/stage.')
return lines.join('\n')
}
async function showPrintPreflightModal (content: string): Promise<void> {
return new Promise((resolve, reject) => {
uni.showModal({
title: 'Print preflight',
content,
confirmText: 'Continue',
cancelText: 'Cancel',
success: (res) => {
if (res.confirm) resolve()
else reject(new Error('CANCEL'))
},
fail: () => reject(new Error('FAIL')),
})
})
}
async function showPrintResultModal (meta?: {
jobId?: number
route?: string
stage?: string
}): Promise<void> {
try {
try { uni.hideLoading() } catch (_) {}
const nativeStateBefore = getNativeFastPrinterState() || {}
const snap = await getPrinterDebugSnapshot({ reason: 'after-print' })
const native = (snap as any)?.nativeFastPrinter || {}
const nativeStateAfter = getNativeFastPrinterState() || {}
const lines: string[] = []
lines.push('Native-fast-printer')
if (native.backend) lines.push(`- backend: ${String(native.backend)}`)
if (native.pluginVersion) lines.push(`- pluginVersion: ${String(native.pluginVersion)}`)
if (native.buildTime) lines.push(`- buildTime: ${String(native.buildTime)}`)
lines.push(`- stage: ${String(native.stage || '-')}`)
lines.push(`- lastError: ${String(native.lastError || '-')}`)
lines.push(`- commandBytes: ${String(native.commandBytes ?? '-')}`)
lines.push(`- writeMs: ${String(native.writeMs ?? '-')}`)
if (meta?.jobId || meta?.route || meta?.stage) {
lines.push('')
lines.push('Print job meta')
lines.push(`- jobId: ${String(meta?.jobId ?? '-')}`)
lines.push(`- route: ${String(meta?.route || '-')}`)
lines.push(`- stage: ${String(meta?.stage || '-')}`)
}
const imageDebug = getLastImagePrintDebug()
if (imageDebug) {
lines.push('')
lines.push('Image raster debug')
lines.push(`- protocol: ${String(imageDebug.protocol)}`)
lines.push(`- size: ${String(imageDebug.rasterWidth)}x${String(imageDebug.rasterHeight)}`)
lines.push(`- blackPixels: ${String(imageDebug.blackPixels)}/${String(imageDebug.totalPixels)}`)
lines.push(`- blackRatio: ${String((imageDebug.blackRatio * 100).toFixed(2))}%`)
lines.push(`- commandBytes(JS): ${String(imageDebug.commandBytes)}`)
}
if (nativeStateBefore && Object.keys(nativeStateBefore).length > 0) {
lines.push('')
lines.push('Native-fast-printer (JS state BEFORE getDebugInfo)')
lines.push(`- lastAction: ${String((nativeStateBefore as any).lastAction || '-')}`)
lines.push(`- stage: ${String((nativeStateBefore as any).stage || '-')}`)
lines.push(`- lastError: ${String((nativeStateBefore as any).lastError || '-')}`)
lines.push(`- commandBytes: ${String((nativeStateBefore as any).commandBytes ?? '-')}`)
lines.push(`- writeMs: ${String((nativeStateBefore as any).writeMs ?? '-')}`)
lines.push('')
lines.push('Native-fast-printer (JS state AFTER getDebugInfo)')
lines.push(`- lastAction: ${String((nativeStateAfter as any).lastAction || '-')}`)
lines.push(`- stage: ${String((nativeStateAfter as any).stage || '-')}`)
lines.push(`- lastError: ${String((nativeStateAfter as any).lastError || '-')}`)
lines.push(`- commandBytes: ${String((nativeStateAfter as any).commandBytes ?? '-')}`)
lines.push(`- writeMs: ${String((nativeStateAfter as any).writeMs ?? '-')}`)
}
lines.push('')
lines.push('Built-in route (detected)')
lines.push(`- uposSupported: ${snap.builtin?.uposSupported ? 'YES' : 'NO'}`)
lines.push(`- uposWillTry: ${snap.builtin?.uposWillTry ? 'YES' : 'NO'}`)
if (snap.builtin?.uposOptions) {
lines.push(`- uposPrefer: ${String(snap.builtin.uposOptions.prefer || '-')}`)
lines.push(`- uposSerialPath: ${String(snap.builtin.uposOptions.serialPath || '-')}`)
lines.push(`- uposBaudrate: ${String(snap.builtin.uposOptions.baudrate || '-')}`)
lines.push(`- uposForce: ${snap.builtin.uposOptions.force ? 'YES' : 'NO'}`)
}
lines.push(`- tcpPluginAvailable: ${snap.builtin?.tcpPluginAvailable ? 'YES' : 'NO'}`)
lines.push(`- savedPort: ${String(snap.builtin?.savedPort || '-')}`)
await new Promise<void>((resolve) => {
uni.showModal({
title: 'Print result',
content: lines.join('\n'),
showCancel: false,
success: () => resolve(),
fail: () => resolve(),
})
})
} catch (_) {}
}
let activePrintJobId = 0
let printJobSeed = 0
function createPrintJobId (): number {
printJobSeed += 1
activePrintJobId = printJobSeed
return activePrintJobId
}
function isPrintJobActive (jobId: number): boolean {
return jobId === activePrintJobId
}
function ensurePrintJobActive (jobId: number) {
if (!isPrintJobActive(jobId)) {
throw new Error('PRINT_JOB_STALE')
}
}
function templateHasQrDataForCommandPrint(tmpl: SystemLabelTemplate): boolean {
const els = tmpl.elements || []
for (const el of els) {
const type = String(el.type || '').toUpperCase()
if (type !== 'QRCODE') continue
const cfg = (el.config || {}) as Record<string, unknown>
const raw = String(
cfg.data ?? cfg.Data ?? cfg.value ?? cfg.Value ?? cfg.src ?? cfg.Src ?? cfg.url ?? cfg.Url ?? ''
).trim()
if (!raw) continue
if (storedValueLooksLikeImagePath(raw)) continue
return true
}
return false
}
function templateHasUnsupportedElementsForCommandPrint(tmpl: SystemLabelTemplate): boolean {
const els = tmpl.elements || []
for (const el of els) {
const type = String(el.type || '').toUpperCase()
if (type.startsWith('TEXT_')) continue
if (
type === 'WEIGHT'
|| type === 'DATE'
|| type === 'TIME'
|| type === 'DURATION'
|| type === 'NUTRITION'
|| type === 'QRCODE'
|| type === 'BARCODE'
|| type === 'IMAGE'
|| type === 'BLANK'
) {
continue
}
return true
}
return false
}
function withTimeout<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {
return new Promise<T>((resolve, reject) => {
const tid = setTimeout(() => reject(new Error(message)), ms)
promise.then(
(v) => { clearTimeout(tid); resolve(v) },
(e) => { clearTimeout(tid); reject(e) },
)
})
}
function applyNativeTemplateStyleScale(
template: SystemLabelTemplate,
options: { textScale?: number; xScale?: number; safeRightRatio?: number }
): SystemLabelTemplate {
const xScale = Number.isFinite(options?.xScale) && (options?.xScale as number) > 0
? (options?.xScale as number)
: 1
const safeRightRatio = Number.isFinite(options?.safeRightRatio) && (options?.safeRightRatio as number) > 0
? Number(options?.safeRightRatio)
: 0.94
const scaleXNum = (v: unknown): unknown => {
const n = Number(v)
if (!Number.isFinite(n)) return v
return Math.round(n * xScale * 1000) / 1000
}
const extras: SystemTemplateElementBase[] = []
const elements = (template.elements || []).map((el) => {
const next: any = { ...el }
next.x = scaleXNum(next.x)
next.width = scaleXNum(next.width)
const type = String(next.type || '').toUpperCase()
const cfg = { ...((next.config || {}) as Record<string, unknown>) }
if (type.startsWith('TEXT_') || type === 'NUTRITION' || type === 'DATE' || type === 'TIME' || type === 'DURATION') {
// 保持字号完全由模板 JSON 控制,不再做全局字体缩放。
cfg.fontWeight = 'normal'
cfg.FontWeight = 'normal'
const sourceType = String(cfg.nativeSourceType || '').toUpperCase()
if (sourceType === 'DATE' || sourceType === 'TIME' || sourceType === 'DURATION') {
// 时间/日期类右对齐文本在部分机型原生 TEXT 宽度估算有误差,强制位图可避免截断。
cfg.forceRasterText = true
}
}
if (type === 'BARCODE') {
const raw = String(
cfg.data ?? cfg.Data ?? cfg.value ?? cfg.Value ?? cfg.src ?? cfg.Src ?? cfg.url ?? cfg.Url ?? ''
).trim()
cfg.showText = false
cfg.ShowText = false
if (raw) {
const ex: any = {
id: `${String(next.id || 'barcode')}_label`,
type: 'TEXT_STATIC',
x: Number(next.x || 0),
y: Number(next.y || 0) + Number(next.height || 0) + 8,
width: Number(next.width || 0),
height: 20,
config: {
text: raw,
fontSize: 12,
fontWeight: 'normal',
textAlign: 'center',
TextAlign: 'center',
/** 纯数字走原生 TEXT 时宽度估算偏大,居中会变成贴左;位图用 measureText 与预览一致 */
forceRasterText: true,
},
}
extras.push(ex as SystemTemplateElementBase)
}
}
if (type === 'NUTRITION') {
cfg.nutritionTitleBold = false
cfg.nutritionBodyBold = false
}
next.config = cfg
return next as SystemTemplateElementBase
})
const allElements = [...elements, ...extras]
const scaledWidthNum = Number(scaleXNum((template as any).width))
if (Number.isFinite(scaledWidthNum) && scaledWidthNum > 0 && allElements.length) {
const safeRight = scaledWidthNum * safeRightRatio
const maxRight = allElements.reduce((acc, el) => {
const x = Number((el as any).x || 0)
const w = Number((el as any).width || 0)
if (!Number.isFinite(x) || !Number.isFinite(w)) return acc
return Math.max(acc, x + w)
}, 0)
/** 不再整体左移 x:与屏幕预览不一致且营养表会像「贴左、右边框丢失」。仅收窄超出安全右界的元素宽度 */
const overflow = Math.max(0, maxRight - safeRight)
if (overflow > 0.01) {
allElements.forEach((el) => {
const t = String((el as any).type || '').toUpperCase()
/** BARCODE/QRCODE 的 width 直接参与原生 narrow/wide 或模块尺寸;收窄会导致「条码缩成一条」 */
if (t === 'BARCODE' || t === 'QRCODE') return
const x = Number((el as any).x || 0)
const w = Number((el as any).width || 0)
if (!Number.isFinite(x) || !Number.isFinite(w)) return
const right = x + w
if (right <= safeRight) return
const room = safeRight - x
if (room <= 0) return
const newW = Math.min(w, Math.max(8, room))
if (newW < w) {
(el as any).width = Math.round(newW * 1000) / 1000
}
})
}
}
return {
...template,
width: scaleXNum((template as any).width) as any,
elements: allElements,
}
}
/** 打印进度:全程 0–100%;节流避免经典蓝牙按块回调时 showLoading 过频卡顿(从 0 第一次前进允许 1%) */
let lastShownPrintPct = -999
function showPrintProgress (percent: number) {
const p = Math.max(0, Math.min(100, Math.round(percent)))
const firstStepFromZero = lastShownPrintPct === 0 && p > 0
if (
!firstStepFromZero &&
p !== 0 &&
p !== 100 &&
Math.abs(p - lastShownPrintPct) < 2
) {
return
}
lastShownPrintPct = p
try {
uni.showLoading({ title: `Printing ${p}%`, mask: true })
} catch (_) {}
}
async function ensureClassicReadyForPrint(): Promise<void> {
const summary = getCurrentPrinterSummary()
const conn = getBluetoothConnection()
if (summary.type !== 'bluetooth' || conn?.deviceType !== 'classic') return
await ensureNativeClassicTransportIfPossible()
await new Promise<void>((resolve, reject) => {
const tryConnect = typeof classicBluetooth?.connDevice === 'function'
if (!tryConnect) {
reject(new Error('CLASSIC_CONNECT_API_MISSING'))
return
}
let settled = false
const timeoutId = setTimeout(() => {
if (settled) return
settled = true
reject(new Error('CLASSIC_CONNECT_TIMEOUT'))
}, 8000)
try {
classicBluetooth.connDevice(conn.deviceId, (ok: boolean) => {
if (settled) return
settled = true
clearTimeout(timeoutId)
if (ok) resolve()
else reject(new Error(classicBluetooth.getLastError?.() || 'CLASSIC_CONNECT_FAILED'))
})
} catch (e: any) {
if (settled) return
settled = true
clearTimeout(timeoutId)
reject(e instanceof Error ? e : new Error(String(e || 'CLASSIC_CONNECT_EXCEPTION')))
}
})
}
const labelCode = ref('')
const productId = ref('')
const displayProductName = ref('')
const productCategory = ref('')
const labelTypeName = ref('')
const templateSize = ref('')
const templateName = ref('')
const lastEdited = ref('')
const locationName = ref('')
const labelIdDisplay = ref('')
const previewLoading = ref(true)
const previewError = ref('')
const previewImageSrc = ref('')
const systemTemplate = ref<SystemLabelTemplate | null>(null)
/** 未合并「打印多选项」前的模板,用于反复 merge */
const basePreviewTemplate = ref<SystemLabelTemplate | null>(null)
const printOptionSelections = ref<Record<string, string[]>>({})
const dictLabelsByElementId = ref<Record<string, string>>({})
const dictValuesByElementId = ref<Record<string, string[]>>({})
const printFreeFieldValues = ref<Record<string, string>>({})
const pickerDialogVisible = ref(false)
const pickerMode = ref<'date' | 'time' | 'datetime'>('date')
const pickerSelection = ref<number[]>([0, 0, 0, 0, 0])
const pickerTargetId = ref('')
const pickerTargetKind = ref<'date' | 'time' | 'datetime'>('date')
const pickerTargetFormat = ref('')
const pickerDialogTitle = computed(() => {
if (pickerMode.value === 'datetime') return 'Select date & time'
if (pickerMode.value === 'date') return 'Select date'
return 'Select time'
})
const pickerYears = computed(() => {
const now = new Date().getFullYear()
return Array.from({ length: 21 }, (_, i) => String(now - 10 + i))
})
const pickerMonths = computed(() => Array.from({ length: 12 }, (_, i) => String(i + 1).padStart(2, '0')))
const pickerHours = computed(() => Array.from({ length: 24 }, (_, i) => String(i).padStart(2, '0')))
const pickerMinutes = computed(() => Array.from({ length: 60 }, (_, i) => String(i).padStart(2, '0')))
/** 与 `.picker-item` 行高一致(px),否则各列与中间选中带错位,看起来像未水平对齐 */
const pickerIndicatorStyle = computed(() => {
const h = uni.upx2px(72)
return `height:${h}px;box-sizing:border-box;`
})
const pickerDays = computed(() => {
if (pickerMode.value !== 'date' && pickerMode.value !== 'datetime') return []
const year = Number(pickerYears.value[pickerSelection.value[0]] || new Date().getFullYear())
const month = Number(pickerMonths.value[pickerSelection.value[1]] || 1)
const dayCount = new Date(year, month, 0).getDate()
return Array.from({ length: dayCount }, (_, i) => String(i + 1).padStart(2, '0'))
})
let freeFieldPreviewTimer: ReturnType<typeof setTimeout> | null = null
const printOptionFieldList = computed(() => {
const t = basePreviewTemplate.value
if (!t?.elements?.length) return []
return t.elements.filter(isPrintInputOptionsElement)
})
const printFreeFieldList = computed(() => {
const t = basePreviewTemplate.value
if (!t?.elements?.length) return []
return t.elements.filter(isPrintInputFreeFieldElement)
})
function dictValuesForElement(elementId: string): string[] {
return dictValuesByElementId.value[elementId] || []
}
function optionFieldTitle(el: SystemTemplateElementBase): string {
return (
dictLabelsByElementId.value[el.id] ||
el.elementName ||
el.inputKey ||
'Options'
)
}
function isOptionPicked(elementId: string, value: string): boolean {
return (printOptionSelections.value[elementId] || []).includes(value)
}
function togglePrintOption(elementId: string, value: string) {
const cur = { ...printOptionSelections.value }
const arr = [...(cur[elementId] || [])]
const i = arr.indexOf(value)
if (i >= 0) arr.splice(i, 1)
else arr.push(value)
if (arr.length) cur[elementId] = arr
else delete cur[elementId]
printOptionSelections.value = cur
void refreshPreviewFromSelections()
}
function freeFieldNameLabel(el: SystemTemplateElementBase): string {
const n = el.elementName || el.inputKey || 'Field'
return `${n}:`
}
function freeFieldPlaceholder(el: SystemTemplateElementBase): string {
const c = el.config || {}
const type = String(el.type || '').toUpperCase()
if (type === 'DATE' || type === 'TIME') {
return String(c.format ?? c.Format ?? '')
}
return ''
}
function freeFieldDateFormat(el: SystemTemplateElementBase): string {
const c = el.config || {}
return String(c.format ?? c.Format ?? '').trim()
}
function freeFieldInputKind(el: SystemTemplateElementBase): 'text' | 'date' | 'time' | 'datetime' {
const type = String(el.type || '').toUpperCase()
const c = el.config || {}
const inputType = String(c.inputType ?? c.InputType ?? '').toLowerCase()
if (type === 'TIME') return 'time'
if (type === 'DATE' && inputType === 'datetime') return 'datetime'
if (type === 'DATE') return 'date'
return 'text'
}
function todayYmd(): string {
const d = new Date()
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${y}-${m}-${day}`
}
function pickerDateValue(raw: string | undefined, format: string): string {
const v = String(raw || '').trim()
if (!v) return todayYmd()
const datePart = v.split(' ')[0]
if (/^\d{4}-\d{2}-\d{2}$/.test(datePart)) return datePart
if (/^\d{2}\/\d{2}\/\d{4}$/.test(datePart)) {
const [a, b, c] = datePart.split('/')
if (format.startsWith('DD/')) return `${c}-${b}-${a}`
return `${c}-${a}-${b}`
}
return todayYmd()
}
function pickerTimeValue(raw: string | undefined): string {
const v = String(raw || '').trim()
const m = v.match(/(\d{2}:\d{2})/)
return m?.[1] || '12:00'
}
function formatYmdByPattern(ymd: string, format: string): string {
const [y, m, d] = ymd.split('-')
if (!y || !m || !d) return ymd
if (format.startsWith('DD/')) return `${d}/${m}/${y}`
if (format.startsWith('MM/')) return `${m}/${d}/${y}`
return `${y}-${m}-${d}`
}
function displayDateValue(raw: string | undefined, format: string, fallback: string): string {
const v = String(raw || '').trim()
if (v) return v.split(' ')[0]
return fallback || 'Select date'
}
function displayTimeValue(raw: string | undefined): string {
const v = String(raw || '').trim()
const m = v.match(/(\d{2}:\d{2})/)
return m?.[1] || 'Select time'
}
function displayDateTimeField(raw: string | undefined, format: string): string {
const v = String(raw || '').trim()
if (v) return v
const f = String(format || '').trim()
return f || 'Select date & time'
}
function dateFormatFromTemplateFormat(full: string): string {
const s = String(full || '').trim()
if (!s) return 'YYYY-MM-DD'
const head = s.split(/\s+/)[0] || ''
if (/Y|M|D/.test(head)) return head
return 'YYYY-MM-DD'
}
function parseExistingDateParts(raw: string): { y: string; m: string; d: string } {
const v = String(raw || '').trim()
if (!v) {
const t = todayYmd().split('-')
return { y: t[0], m: t[1], d: t[2] }
}
const datePart = v.split(' ')[0]
if (/^\d{4}-\d{2}-\d{2}$/.test(datePart)) {
const [y, m, d] = datePart.split('-')
return { y, m, d }
}
if (/^\d{2}\/\d{2}\/\d{4}$/.test(datePart)) {
const [a, b, c] = datePart.split('/')
return { y: c, m: b, d: a }
}
const t = todayYmd().split('-')
return { y: t[0], m: t[1], d: t[2] }
}
function openFreeFieldPicker(el: SystemTemplateElementBase, mode: 'date' | 'time' | 'datetime') {
pickerTargetId.value = el.id
pickerTargetKind.value = freeFieldInputKind(el)
pickerTargetFormat.value = freeFieldDateFormat(el)
pickerMode.value = mode
const currentRaw = String(printFreeFieldValues.value[el.id] || '').trim()
if (mode === 'date') {
const p = parseExistingDateParts(currentRaw)
const yi = Math.max(0, pickerYears.value.indexOf(p.y))
const mi = Math.max(0, pickerMonths.value.indexOf(p.m))
const dd = Array.from({ length: new Date(Number(p.y), Number(p.m), 0).getDate() }, (_, i) => String(i + 1).padStart(2, '0'))
const di = Math.max(0, dd.indexOf(p.d))
pickerSelection.value = [yi, mi, di]
} else if (mode === 'datetime') {
const p = parseExistingDateParts(currentRaw)
const yi = Math.max(0, pickerYears.value.indexOf(p.y))
const mi = Math.max(0, pickerMonths.value.indexOf(p.m))
const dd = Array.from({ length: new Date(Number(p.y), Number(p.m), 0).getDate() }, (_, i) => String(i + 1).padStart(2, '0'))
const di = Math.max(0, dd.indexOf(p.d))
const hhmm = pickerTimeValue(currentRaw).split(':')
const hi = Math.max(0, pickerHours.value.indexOf(hhmm[0] || '12'))
const mini = Math.max(0, pickerMinutes.value.indexOf(hhmm[1] || '00'))
pickerSelection.value = [yi, mi, di, hi, mini]
} else {
const hhmm = pickerTimeValue(currentRaw).split(':')
const hi = Math.max(0, pickerHours.value.indexOf(hhmm[0] || '12'))
const mi = Math.max(0, pickerMinutes.value.indexOf(hhmm[1] || '00'))
pickerSelection.value = [hi, mi]
}
pickerDialogVisible.value = true
}
function closeFreeFieldPicker() {
pickerDialogVisible.value = false
}
function onPickerViewChange(e: { detail?: { value?: number[] } }) {
const raw = e.detail?.value
if (!Array.isArray(raw)) {
pickerSelection.value = []
return
}
if (pickerMode.value === 'time') {
pickerSelection.value = raw.slice(0, 2)
return
}
let arr = [...raw]
if (pickerMode.value === 'date') arr = arr.slice(0, 3)
else if (pickerMode.value === 'datetime') arr = arr.slice(0, 5)
const yi = arr[0] ?? 0
const mi = arr[1] ?? 0
const y = Number(pickerYears.value[yi] || new Date().getFullYear())
const mo = Number(pickerMonths.value[mi] || 1)
const dayCount = new Date(y, mo, 0).getDate()
const maxDi = Math.max(0, dayCount - 1)
if (arr.length >= 3 && (arr[2] ?? 0) > maxDi) arr[2] = maxDi
pickerSelection.value = arr
}
function confirmFreeFieldPicker() {
const id = pickerTargetId.value
if (!id) {
pickerDialogVisible.value = false
return
}
const prev = String(printFreeFieldValues.value[id] || '').trim()
const dateFmt = dateFormatFromTemplateFormat(pickerTargetFormat.value)
if (pickerMode.value === 'datetime') {
const y = pickerYears.value[pickerSelection.value[0]] || String(new Date().getFullYear())
const mo = pickerMonths.value[pickerSelection.value[1]] || '01'
const maxDi = Math.max(0, pickerDays.value.length - 1)
const di = Math.min(Math.max(0, pickerSelection.value[2] || 0), maxDi)
const d = pickerDays.value[di] || '01'
const h = pickerHours.value[pickerSelection.value[3]] || '12'
const min = pickerMinutes.value[pickerSelection.value[4]] || '00'
const formatted = formatYmdByPattern(`${y}-${mo}-${d}`, dateFmt)
printFreeFieldValues.value = { ...printFreeFieldValues.value, [id]: `${formatted} ${h}:${min}` }
} else if (pickerMode.value === 'date') {
const y = pickerYears.value[pickerSelection.value[0]] || String(new Date().getFullYear())
const m = pickerMonths.value[pickerSelection.value[1]] || '01'
const d = pickerDays.value[pickerSelection.value[2]] || '01'
const formatted = formatYmdByPattern(`${y}-${m}-${d}`, dateFmt)
if (pickerTargetKind.value === 'datetime') {
const timePart = pickerTimeValue(prev)
printFreeFieldValues.value = { ...printFreeFieldValues.value, [id]: `${formatted} ${timePart}` }
} else {
printFreeFieldValues.value = { ...printFreeFieldValues.value, [id]: formatted }
}
} else {
const h = pickerHours.value[pickerSelection.value[0]] || '12'
const m = pickerMinutes.value[pickerSelection.value[1]] || '00'
const hhmm = `${h}:${m}`
if (pickerTargetKind.value === 'datetime') {
const datePart = prev.split(' ')[0] || formatYmdByPattern(todayYmd(), dateFmt)
printFreeFieldValues.value = { ...printFreeFieldValues.value, [id]: `${datePart} ${hhmm}` }
} else {
printFreeFieldValues.value = { ...printFreeFieldValues.value, [id]: hhmm }
}
}
if (freeFieldPreviewTimer != null) clearTimeout(freeFieldPreviewTimer)
freeFieldPreviewTimer = setTimeout(() => {
freeFieldPreviewTimer = null
void refreshPreviewFromSelections()
}, 180)
pickerDialogVisible.value = false
}
function onFreeFieldDateChange(el: SystemTemplateElementBase, e: { detail?: { value?: string } }) {
const ymd = String(e.detail?.value || '').trim()
if (!ymd) return
const id = el.id
const kind = freeFieldInputKind(el)
const formatted = formatYmdByPattern(ymd, freeFieldDateFormat(el))
const prev = String(printFreeFieldValues.value[id] || '').trim()
if (kind === 'datetime') {
const timePart = pickerTimeValue(prev)
printFreeFieldValues.value = { ...printFreeFieldValues.value, [id]: `${formatted} ${timePart}` }
} else {
printFreeFieldValues.value = { ...printFreeFieldValues.value, [id]: formatted }
}
if (freeFieldPreviewTimer != null) clearTimeout(freeFieldPreviewTimer)
freeFieldPreviewTimer = setTimeout(() => {
freeFieldPreviewTimer = null
void refreshPreviewFromSelections()
}, 180)
}
function onFreeFieldTimeChange(elementId: string, e: { detail?: { value?: string } }) {
const timeVal = String(e.detail?.value || '').trim()
if (!timeVal) return
const prev = String(printFreeFieldValues.value[elementId] || '').trim()
const datePart = prev.split(' ')[0] || formatYmdByPattern(todayYmd(), 'YYYY-MM-DD')
printFreeFieldValues.value = { ...printFreeFieldValues.value, [elementId]: `${datePart} ${timeVal}` }
if (freeFieldPreviewTimer != null) clearTimeout(freeFieldPreviewTimer)
freeFieldPreviewTimer = setTimeout(() => {
freeFieldPreviewTimer = null
void refreshPreviewFromSelections()
}, 180)
}
function onFreeFieldInput(elementId: string, e: { detail?: { value?: string } }) {
const v = e.detail?.value ?? ''
printFreeFieldValues.value = { ...printFreeFieldValues.value, [elementId]: v }
if (freeFieldPreviewTimer != null) clearTimeout(freeFieldPreviewTimer)
freeFieldPreviewTimer = setTimeout(() => {
freeFieldPreviewTimer = null
void refreshPreviewFromSelections()
}, 280)
}
function computeMergedPreviewTemplate(): SystemLabelTemplate | null {
const base = basePreviewTemplate.value
if (!base) return null
let m = mergePrintOptionSelections(
base,
printOptionSelections.value,
dictLabelsByElementId.value
)
m = mergePrintInputFreeFields(m, printFreeFieldValues.value)
return m
}
async function loadDictionaryMetaForTemplate(t: SystemLabelTemplate) {
const labels: Record<string, string> = {}
const values: Record<string, string[]> = {}
for (const el of t.elements || []) {
if (!isPrintInputOptionsElement(el)) continue
const mid = String(el.config?.multipleOptionId ?? el.config?.MultipleOptionId ?? '').trim()
if (!mid) continue
try {
const d = await fetchLabelMultipleOptionById(mid)
if (d) {
labels[el.id] = d.optionName
values[el.id] = d.optionValuesJson.length ? d.optionValuesJson : []
}
} catch {
values[el.id] = []
}
}
dictLabelsByElementId.value = labels
dictValuesByElementId.value = values
}
/** 画布 :width/:height 与离屏节点布局在 H5 上晚一拍,过早 canvasToTempFilePath 会裁切底部;双 nextTick + 双 rAF 再导出 */
async function waitForCanvasLayout(): Promise<void> {
await nextTick()
await nextTick()
await new Promise<void>((resolve) => {
if (typeof requestAnimationFrame === 'function') {
requestAnimationFrame(() => {
requestAnimationFrame(() => resolve())
})
} else {
setTimeout(() => resolve(), 32)
}
})
}
/** 光栅打印前同步隐藏 canvas 像素尺寸,避免缓冲区高度仍为预览值导致底部裁切 */
async function applyPrintCanvasLayout(layout: { outW: number; outH: number }) {
canvasCssW.value = layout.outW
canvasCssH.value = layout.outH
await waitForCanvasLayout()
await new Promise<void>((r) => setTimeout(r, 80))
}
let deferredPreviewRedrawTimer: ReturnType<typeof setTimeout> | null = null
/** 首屏内容与 loading 切换后布局才稳定,补绘一次与「改输入后变正常」同路径 */
function scheduleDeferredPreviewRedraw() {
if (deferredPreviewRedrawTimer != null) clearTimeout(deferredPreviewRedrawTimer)
deferredPreviewRedrawTimer = setTimeout(() => {
deferredPreviewRedrawTimer = null
void refreshPreviewFromSelections()
}, 120)
}
async function refreshPreviewFromSelections() {
const merged = computeMergedPreviewTemplate()
if (!merged || !instance) return
systemTemplate.value = merged
const sz = getPreviewCanvasCssSize(merged, 720)
canvasCssW.value = sz.width
canvasCssH.value = sz.height
await waitForCanvasLayout()
try {
const path = await renderLabelPreviewToTempPath('labelPreviewCanvas', instance, merged, 720)
previewImageSrc.value = path
} catch {
/* keep previous image */
}
}
const canvasCssW = ref(300)
const canvasCssH = ref(200)
onShow(() => {
btConnected.value = isPrinterReadySync()
const summary = getCurrentPrinterSummary()
const conn = getBluetoothConnection()
if (summary.type === 'bluetooth' && conn?.deviceName) {
btDeviceName.value = conn.deviceName
} else if (summary.type === 'builtin') {
btDeviceName.value = summary.driverName || 'Built-in'
} else {
btDeviceName.value = summary.displayName || ''
}
const name = uni.getStorageSync('storeName')
if (typeof name === 'string' && name.trim()) locationName.value = name.trim()
})
onUnload(() => {
if (deferredPreviewRedrawTimer != null) {
clearTimeout(deferredPreviewRedrawTimer)
deferredPreviewRedrawTimer = null
}
})
onLoad((opts: Record<string, string | undefined>) => {
labelCode.value = decodeURIComponent(opts.labelCode || '')
productId.value = decodeURIComponent(opts.productId || '')
displayProductName.value = decodeURIComponent(opts.productName || '')
productCategory.value = decodeURIComponent(opts.categoryName || '')
labelTypeName.value = decodeURIComponent(opts.typeName || '')
templateSize.value = decodeURIComponent(opts.templateSize || '')
templateName.value = decodeURIComponent(opts.templateName || '')
const name = uni.getStorageSync('storeName')
if (typeof name === 'string' && name.trim()) locationName.value = name.trim()
labelIdDisplay.value = '—'
lastEdited.value = '—'
loadPreview()
})
async function loadPreview() {
const loc = getCurrentStoreId()
if (!loc) {
previewError.value = 'No store selected.'
previewLoading.value = false
return
}
if (!labelCode.value) {
previewError.value = 'Missing label code.'
previewLoading.value = false
return
}
if (deferredPreviewRedrawTimer != null) {
clearTimeout(deferredPreviewRedrawTimer)
deferredPreviewRedrawTimer = null
}
previewLoading.value = true
previewError.value = ''
previewImageSrc.value = ''
systemTemplate.value = null
basePreviewTemplate.value = null
printOptionSelections.value = {}
printFreeFieldValues.value = {}
dictLabelsByElementId.value = {}
dictValuesByElementId.value = {}
try {
const raw = await postUsAppLabelPreview({
locationId: loc,
labelCode: labelCode.value,
productId: productId.value || undefined,
})
const root = raw as Record<string, unknown>
const nested = root.data ?? root.Data
const inner =
nested != null && typeof nested === 'object' && !Array.isArray(nested)
? (nested as Record<string, unknown>)
: null
/** 8.2 预览:labelLastEdited / labelId(兼容 data 嵌套、lastEdited、PascalCase) */
const readLastEdited = (L: Record<string, unknown> | null): string => {
if (!L) return ''
const v =
L.labelLastEdited ??
L.LabelLastEdited ??
L.lastEdited ??
L.LastEdited
return typeof v === 'string' && v.trim() ? v.trim() : ''
}
const readLabelId = (L: Record<string, unknown> | null): string => {
if (!L) return ''
const v = L.labelId ?? L.LabelId
return v != null && String(v).trim() !== '' ? String(v).trim() : ''
}
const leStr = readLastEdited(root) || readLastEdited(inner)
lastEdited.value = leStr || '—'
const lidStr = readLabelId(root) || readLabelId(inner)
if (lidStr) labelIdDisplay.value = lidStr
const tmplPayload =
inner != null &&
(inner.template != null ||
inner.Template != null ||
Array.isArray(inner.elements) ||
Array.isArray(inner.Elements))
? inner
: raw
const tmplRaw = normalizeLabelTemplateFromPreviewApi(tmplPayload)
if (!tmplRaw) {
previewError.value = 'Invalid preview template.'
previewLoading.value = false
return
}
const lstRaw =
root.labelSizeText ??
root.LabelSizeText ??
inner?.labelSizeText ??
inner?.LabelSizeText
const labelSizeTextFromApi = typeof lstRaw === 'string' ? lstRaw : null
if (labelSizeTextFromApi && labelSizeTextFromApi.trim()) {
templateSize.value = labelSizeTextFromApi.trim()
}
const productDefaults = extractTemplateProductDefaultValuesFromPreviewPayload(raw)
let tmplWithDefaults =
Object.keys(productDefaults).length > 0
? applyTemplateProductDefaultValuesToTemplate(tmplRaw, productDefaults)
: tmplRaw
const productCodeValue = extractProductCodeValueFromPreviewPayload(raw)
if (productCodeValue) {
tmplWithDefaults = applyProductCodeValueToTemplateScanElements(
tmplWithDefaults,
productCodeValue,
)
}
/** 画布像素仅按接口 template 的 width / height / unit 换算(与 renderLabelPreviewCanvas.toCanvasPx 一致),不用 labelSizeText 覆盖以免单位被误判 */
const base = overlayProductNameOnPreviewTemplate(tmplWithDefaults, displayProductName.value)
basePreviewTemplate.value = base
printOptionSelections.value = readSelectionsFromTemplate(base)
printFreeFieldValues.value = ensureFreeFieldKeys(base, readFreeFieldValuesFromTemplate(base))
await loadDictionaryMetaForTemplate(base)
const merged = computeMergedPreviewTemplate()
if (!merged) {
previewError.value = 'Invalid preview template.'
previewLoading.value = false
return
}
systemTemplate.value = merged
const sz = getPreviewCanvasCssSize(merged, 720)
canvasCssW.value = sz.width
canvasCssH.value = sz.height
await waitForCanvasLayout()
if (!instance) {
previewError.value = 'Preview unavailable.'
previewLoading.value = false
return
}
const path = await renderLabelPreviewToTempPath('labelPreviewCanvas', instance, merged, 720)
previewImageSrc.value = path
scheduleDeferredPreviewRedraw()
} catch (e: unknown) {
if (isUsAppSessionExpiredError(e)) return
previewError.value = e instanceof Error ? e.message : 'Preview failed.'
} finally {
previewLoading.value = false
}
}
const increment = () => {
if (printQty.value < 99) printQty.value++
}
const decrement = () => {
if (printQty.value > 1) printQty.value--
}
const goBack = () => uni.navigateBack()
const goBluetoothPage = () => {
uni.navigateTo({ url: '/pages/labels/bluetooth' })
}
/** 接口 9 可选 clientRequestId(文档 10 幂等) */
function createPrintClientRequestId (): string {
const c = typeof globalThis !== 'undefined' ? (globalThis as { crypto?: Crypto }).crypto : undefined
if (c && typeof c.randomUUID === 'function') {
return c.randomUUID()
}
return `print-${Date.now()}-${Math.random().toString(36).slice(2, 12)}`
}
const handlePrint = async () => {
if (isPrinting.value || previewLoading.value || !systemTemplate.value) return
if (!isPrinterReadySync()) {
showNoPrinterModal.value = true
return
}
const tmplForValidate = basePreviewTemplate.value ?? systemTemplate.value
if (tmplForValidate) {
const optErr = validatePrintInputOptionsBeforePrint(
tmplForValidate,
printOptionSelections.value,
dictLabelsByElementId.value
)
if (optErr) {
uni.showToast({ title: optErr, icon: 'none', duration: 3000 })
return
}
const freeErr = validatePrintInputFreeFieldsBeforePrint(
tmplForValidate,
printFreeFieldValues.value
)
if (freeErr) {
uni.showToast({ title: freeErr, icon: 'none', duration: 3000 })
return
}
}
try {
await ensureClassicReadyForPrint()
} catch (e: any) {
const msg = e?.message ? String(e.message) : 'CLASSIC_NOT_READY'
uni.showModal({
title: 'Printer Not Ready',
content: `${msg}\n\n${buildPrintDebugText({ stage: 'preflight' })}`.trim(),
showCancel: false,
})
return
}
// Virtual BT Printer 在当前基座缺少 native-fast-printer 插件时容易出现“发送中卡死”。
// 先 fail-fast,避免进入长时间无响应流程。
const summaryPreflight = getCurrentPrinterSummary()
const connPreflight = getBluetoothConnection()
const isVirtualBtPrinter = String(connPreflight?.deviceName || '').toLowerCase().includes('virtual bt printer')
if (
summaryPreflight.type === 'bluetooth' &&
summaryPreflight.driverKey === 'd320fax' &&
isVirtualBtPrinter &&
!isNativeFastPrinterAvailable()
) {
uni.showModal({
title: 'Print Not Supported In Current Build',
content:
'Virtual BT Printer (D320FAX) requires native-fast-printer in this app build. Please use a build that includes this plugin, or switch to a non-virtual Bluetooth printer.',
showCancel: false,
})
return
}
isPrinting.value = true
const printJobId = createPrintJobId()
let watchdog: ReturnType<typeof setTimeout> | null = null
let globalWatchdog: ReturnType<typeof setTimeout> | null = null
const startedAt = Date.now()
let printStage = 'start'
let printRoute = '-'
let timeoutHandledByWatchdog = false
let printResultShown = false
const showPrintResultOnce = async () => {
if (printResultShown) return
printResultShown = true
await showPrintResultModal({
jobId: printJobId,
route: printRoute,
stage: printStage,
})
}
try {
lastShownPrintPct = -999
uni.showLoading({ title: 'Rendering…', mask: true })
/** 按 label-template-*.json 结构组装 template + printInputJson;出纸与 Test Print 相同:PNG → Bitmap → TSC → BLE */
const mergedForPrint = computeMergedPreviewTemplate()
const tmplBase = mergedForPrint ?? systemTemplate.value
if (!tmplBase || !instance) {
throw new Error('No label to print.')
}
const tmpl = ensureTemplateHeightCoversElements(tmplBase)
const phys = getTemplatePhysicalSizeMm(tmpl)
console.info(
'[preview] print physical size',
`${phys.widthMm}×${phys.heightMm}mm`,
`template=${tmpl.width}×${tmpl.height}${phys.unit}`,
)
ensurePrintJobActive(printJobId)
const printInputJson = buildPrintInputJson(
tmpl,
printOptionSelections.value,
printFreeFieldValues.value
)
printStage = 'payload-ready'
/**
* 经典蓝牙 + native-plugin(含 Virtual BT):走原生 printTemplate(JSON,快,与预览坐标一致)。
* Virtual BT 不做 xScale/安全区收窄(易导致营养表错位、条码丢失);光栅仅作回退。
* 普通蓝牙(BLE 或 classic+JS socket):canPrintCurrentLabelViaNativeFastJob 为 false,走下方光栅/直发 TSC。
*/
const tmplForNativeJob = normalizeTemplateForNativeFastJob(tmpl, printInputJson as any)
const currentDriver = getCurrentPrinterDriver()
const currentConn = getBluetoothConnection()
const isD320faxClassicNative =
currentDriver.key === 'd320fax' && currentConn?.deviceType === 'classic'
const useNativeTemplatePrint =
canPrintCurrentLabelViaNativeFastJob()
&& isTemplateWithinNativeFastPrintBounds(tmpl)
&& !templateHasUnsupportedNativeFastElements(tmplForNativeJob)
if (ENABLE_PRINT_PREFLIGHT_MODAL) {
// 一体机无 console:打印前弹设备链路信息(仅调试模式开启)
try {
const printerSnap = await getPrinterDebugSnapshot({ reason: 'preflight' })
const preflightText = buildPrintPreflightDeviceInfoText({
template: tmpl,
useNativeTemplatePrint,
nativeUnsupported: templateHasUnsupportedNativeFastElements(tmplForNativeJob),
printerSnapshot: printerSnap,
})
await showPrintPreflightModal(preflightText)
} catch {
uni.hideLoading()
if (isPrintJobActive(printJobId)) isPrinting.value = false
return
}
}
ensurePrintJobActive(printJobId)
/** 基座只认本地路径;http(s)、/picture/ 须先下载,否则 IMAGE 整块丢失 */
let tmplForNativePayload = tmplForNativeJob
if (useNativeTemplatePrint) {
// 真机 GP-D320FX 可略收窄;Virtual BT 必须与预览同坐标,禁止 xScale。
if (isD320faxClassicNative && !isVirtualBtPrinter) {
tmplForNativePayload = applyNativeTemplateStyleScale(
tmplForNativePayload,
{ textScale: 1, xScale: 0.9, safeRightRatio: 0.88 },
)
}
resetHydrateImageDebugRecords()
tmplForNativePayload = await hydrateSystemTemplateImagesForPrint(tmplForNativePayload)
}
const labelPrintJobPayload = buildLabelPrintJobPayload(
useNativeTemplatePrint ? tmplForNativePayload : tmpl,
printInputJson,
{
labelCode: labelCode.value,
productId: productId.value || undefined,
printQuantity: printQty.value,
locationId: getCurrentStoreId() || undefined,
},
)
setLastLabelPrintJobPayload(labelPrintJobPayload)
/**
* 原生 printTemplate:物理尺寸超幅宽则回退光栅;规范化后仍有原生未覆盖元素则回退光栅。
*/
if (useNativeTemplatePrint) {
printRoute = 'native-template'
printStage = 'native-print-start'
const builtinNative = getCurrentPrinterSummary().type === 'builtin'
const nativeOuterMs = builtinNative ? 600000 : 40000
const nativeUiWatchdogMs = builtinNative ? nativeOuterMs + 60000 : 45000
showPrintInProgressDebugModal({
jobId: printJobId,
route: printRoute,
stage: printStage,
})
/** 经典蓝牙 + native-plugin:JSON → printTemplate(不经整页光栅,速度优先) */
uni.showLoading({ title: 'Printing…', mask: true })
watchdog = setTimeout(() => {
timeoutHandledByWatchdog = true
try { uni.hideLoading() } catch (_) {}
isPrinting.value = false
console.warn(
'[preview] PRINT_TIMEOUT native-fast',
buildPrintDebugText({ branch: 'native-fast', stage: printStage, elapsedMs: Date.now() - startedAt, qty: printQty.value }),
)
}, nativeUiWatchdogMs)
await withTimeout(printLabelPrintJobPayloadForCurrentPrinter(
labelPrintJobPayload,
{ printQty: printQty.value },
(percent) => {
if (!isPrintJobActive(printJobId)) return
showPrintProgress(percent)
}
), nativeOuterMs, 'PRINT_TIMEOUT')
printStage = 'native-print-done'
if (ENABLE_PRINT_RESULT_MODAL) await showPrintResultOnce()
} else {
printStage = 'raster-layout'
const driver = getCurrentPrinterDriver()
if (driver.key === 'd320fax') {
printRoute = 'd320fax'
const connNow = getBluetoothConnection()
const isVirtualBtPrinter = String(connNow?.deviceName || '').toLowerCase().includes('virtual bt printer')
/** Virtual 整页光栅与屏幕预览同源,可打出 ¥/价格;直发模板在部分环境位图字失败会缺底行 */
/** 大图光栅 + 慢机可能 >8min;与原生 printCommandBytes 对齐后一般会快很多 */
const virtualJobMs = 720000
const nonVirtualRasterMs = 220000
const nonVirtualDirectMs = 480000
const globalCapMs = isVirtualBtPrinter ? 780000 : 540000
const branchWatchMs = isVirtualBtPrinter ? 760000 : 520000
if (globalWatchdog) {
clearTimeout(globalWatchdog)
globalWatchdog = null
}
globalWatchdog = setTimeout(() => {
timeoutHandledByWatchdog = true
try { uni.hideLoading() } catch (_) {}
isPrinting.value = false
console.warn(
'[preview] PRINT_TIMEOUT_GLOBAL d320fax',
buildPrintDebugText({ stage: printStage, elapsedMs: Date.now() - startedAt, qty: printQty.value }),
)
}, globalCapMs)
watchdog = setTimeout(() => {
timeoutHandledByWatchdog = true
try { uni.hideLoading() } catch (_) {}
isPrinting.value = false
console.warn(
'[preview] PRINT_TIMEOUT d320fax',
buildPrintDebugText({ branch: 'd320fax', stage: printStage, elapsedMs: Date.now() - startedAt, qty: printQty.value }),
)
}, branchWatchMs)
if (isVirtualBtPrinter) {
showPrintProgress(0)
try {
printStage = 'd320fax-virtual-raster-start'
await withTimeout(
printSystemTemplateForCurrentPrinter(
tmpl,
printInputJson as any,
{
printQty: printQty.value,
canvasRaster: {
canvasId: 'labelPreviewCanvas',
componentInstance: instance,
applyLayout: applyPrintCanvasLayout,
},
},
(percent) => {
if (!isPrintJobActive(printJobId)) return
showPrintProgress(percent)
},
),
virtualJobMs,
'PRINT_TIMEOUT_RASTER',
)
printStage = 'd320fax-virtual-raster-done'
} catch (e: any) {
const msg = e?.message ? String(e.message) : ''
// 超时时底层可能仍在发送,若立刻回退直发会导致“一次点击出两张”。
if (msg.includes('PRINT_TIMEOUT')) {
throw e
}
printStage = 'd320fax-virtual-direct-fallback-start'
showPrintProgress(0)
await withTimeout(
printSystemTemplateForCurrentPrinter(
tmpl,
printInputJson as any,
{ printQty: printQty.value },
(percent) => {
if (!isPrintJobActive(printJobId)) return
showPrintProgress(percent)
},
),
virtualJobMs,
'PRINT_TIMEOUT_DIRECT',
)
printStage = 'd320fax-virtual-direct-fallback-done'
}
} else {
printStage = 'd320fax-raster-start'
showPrintProgress(0)
try {
await withTimeout(
printSystemTemplateForCurrentPrinter(
tmpl,
printInputJson as any,
{
printQty: printQty.value,
canvasRaster: {
canvasId: 'labelPreviewCanvas',
componentInstance: instance,
applyLayout: applyPrintCanvasLayout,
},
},
(percent) => {
if (!isPrintJobActive(printJobId)) return
showPrintProgress(percent)
},
),
nonVirtualRasterMs,
'PRINT_TIMEOUT_RASTER',
)
printStage = 'd320fax-raster-done'
} catch (e: any) {
const msg = e?.message ? String(e.message) : ''
// 超时时底层可能仍在发送,若立刻回退直发会导致“一次点击出两张”。
if (msg.includes('PRINT_TIMEOUT')) {
throw e
}
printStage = 'd320fax-direct-fallback-start'
showPrintProgress(0)
await withTimeout(
printSystemTemplateForCurrentPrinter(
tmpl,
printInputJson as any,
{ printQty: printQty.value },
(percent) => {
if (!isPrintJobActive(printJobId)) return
showPrintProgress(percent)
},
),
nonVirtualDirectMs,
'PRINT_TIMEOUT_DIRECT_FALLBACK',
)
printStage = 'd320fax-direct-fallback-done'
}
}
} else {
printRoute = 'generic'
const shouldUseDirectTemplate =
driver.protocol === 'tsc' &&
templateHasQrDataForCommandPrint(tmpl) &&
!templateHasUnsupportedElementsForCommandPrint(tmpl)
if (shouldUseDirectTemplate) {
const directJobMs = 240000
if (globalWatchdog) {
clearTimeout(globalWatchdog)
globalWatchdog = null
}
globalWatchdog = setTimeout(() => {
timeoutHandledByWatchdog = true
try { uni.hideLoading() } catch (_) {}
isPrinting.value = false
console.warn(
'[preview] PRINT_TIMEOUT_GLOBAL direct-qrcode',
buildPrintDebugText({ stage: printStage, elapsedMs: Date.now() - startedAt, qty: printQty.value }),
)
}, directJobMs + 60000)
showPrintProgress(0)
watchdog = setTimeout(() => {
timeoutHandledByWatchdog = true
try { uni.hideLoading() } catch (_) {}
isPrinting.value = false
console.warn(
'[preview] PRINT_TIMEOUT direct-qrcode',
buildPrintDebugText({
branch: 'direct-qrcode',
stage: printStage,
elapsedMs: Date.now() - startedAt,
qty: printQty.value,
}),
)
}, directJobMs + 30000)
printStage = 'direct-qrcode-start'
await withTimeout(
printSystemTemplateForCurrentPrinter(
tmpl,
printInputJson as any,
{ printQty: printQty.value },
(percent) => showPrintProgress(percent),
),
directJobMs,
'PRINT_TIMEOUT_DIRECT_QRCODE',
)
printStage = 'direct-qrcode-done'
} else {
const rasterDriver = resolveRasterPrintDriver(driver)
printRoute = rasterDriver.protocol === 'esc' ? 'esc-raster' : 'tsc-raster'
if (globalWatchdog) {
clearTimeout(globalWatchdog)
globalWatchdog = null
}
const maxDots =
rasterDriver.imageMaxWidthDots || (rasterDriver.protocol === 'esc' ? 384 : 576)
const escUseContentH = rasterDriver.protocol === 'esc'
const contentHpx = escUseContentH ? templateContentHeightPx(tmpl) : undefined
const layout = getLabelPrintRasterLayout(
tmpl,
maxDots,
rasterDriver.imageDpi || 203,
contentHpx != null ? { contentHeightPx: contentHpx } : undefined,
)
canvasCssW.value = layout.outW
canvasCssH.value = layout.outH
await nextTick()
await new Promise<void>((r) => setTimeout(r, 50))
const useCanvasRasterPath = shouldRasterPrintViaCanvasImageData()
let tmpPath = ''
if (useCanvasRasterPath) {
try {
printStage = 'raster-canvas-rgba'
const imageData = await renderLabelPreviewCanvasImageDataForPrint(
'labelPreviewCanvas',
instance,
tmpl,
layout
)
printStage = 'raster-image-ready'
showPrintProgress(0)
const genericRasterJobMs = 300000
const escBuiltinLongWatchMs = 900000
const watchdogMs =
rasterDriver.protocol === 'esc' && getCurrentPrinterSummary().type === 'builtin'
? escBuiltinLongWatchMs
: (genericRasterJobMs + 30000)
const rasterGlobalCapMs = watchdogMs + 120000
globalWatchdog = setTimeout(() => {
timeoutHandledByWatchdog = true
try { uni.hideLoading() } catch (_) {}
isPrinting.value = false
console.warn(
'[preview] PRINT_TIMEOUT_GLOBAL raster',
buildPrintDebugText({ stage: printStage, elapsedMs: Date.now() - startedAt, qty: printQty.value }),
)
}, rasterGlobalCapMs)
watchdog = setTimeout(() => {
timeoutHandledByWatchdog = true
try { uni.hideLoading() } catch (_) {}
isPrinting.value = false
console.warn(
'[preview] PRINT_TIMEOUT raster',
buildPrintDebugText({
branch: 'raster',
stage: printStage,
elapsedMs: Date.now() - startedAt,
qty: printQty.value,
outW: layout.outW,
outH: layout.outH,
tmpPath: 'canvas-rgba',
}),
)
}, watchdogMs)
printStage = 'raster-print-start'
showPrintInProgressDebugModal({
jobId: printJobId,
route: printRoute,
stage: printStage,
})
if (rasterDriver.protocol === 'esc') {
await printImageDataForCurrentPrinter(
imageData,
{
printQty: printQty.value,
clearTopRasterRows: 0,
targetWidthDots: layout.outW,
targetHeightDots: layout.outH,
useContentHeight: true,
cutBetweenCopies: true,
},
(percent) => {
if (!isPrintJobActive(printJobId)) return
showPrintProgress(percent)
}
)
} else {
await withTimeout(
printImageDataForCurrentPrinter(
imageData,
{
printQty: printQty.value,
clearTopRasterRows: 1,
targetWidthDots: layout.outW,
targetHeightDots: layout.outH,
labelRasterFixedHeight: true,
},
(percent) => {
if (!isPrintJobActive(printJobId)) return
showPrintProgress(percent)
}
),
genericRasterJobMs,
'PRINT_TIMEOUT'
)
}
printStage = 'raster-print-done'
if (ENABLE_PRINT_RESULT_MODAL) await showPrintResultOnce()
/* 内置已处理完本分支,跳过下方 PNG 光栅 */
tmpPath = '__builtin_canvas_done__'
} catch (e) {
console.warn('[preview] builtin canvasGetImageData failed, fallback PNG raster', e)
tmpPath = ''
}
}
if (tmpPath === '__builtin_canvas_done__') {
/* 内置已在上方完成光栅+下发 */
} else {
tmpPath = tmpPath || await renderLabelPreviewCanvasToTempPathForPrint(
'labelPreviewCanvas',
instance,
tmpl,
layout
)
printStage = 'raster-image-ready'
showPrintProgress(0)
const genericRasterJobMs = 300000
const escBuiltinLongWatchMs = 900000
const watchdogMs =
rasterDriver.protocol === 'esc' && getCurrentPrinterSummary().type === 'builtin'
? escBuiltinLongWatchMs
: (genericRasterJobMs + 30000)
/** 须 ≥ 分支 watchdog,否则内置慢光栅会先被 6min 全局定时器误杀(日志里 PRINT_TIMEOUT_GLOBAL 与 raster 仍在跑并存) */
const rasterGlobalCapMs = watchdogMs + 120000
globalWatchdog = setTimeout(() => {
timeoutHandledByWatchdog = true
try { uni.hideLoading() } catch (_) {}
isPrinting.value = false
console.warn(
'[preview] PRINT_TIMEOUT_GLOBAL raster',
buildPrintDebugText({ stage: printStage, elapsedMs: Date.now() - startedAt, qty: printQty.value }),
)
}, rasterGlobalCapMs)
watchdog = setTimeout(() => {
timeoutHandledByWatchdog = true
try { uni.hideLoading() } catch (_) {}
isPrinting.value = false
console.warn(
'[preview] PRINT_TIMEOUT raster',
buildPrintDebugText({
branch: 'raster',
stage: printStage,
elapsedMs: Date.now() - startedAt,
qty: printQty.value,
outW: layout.outW,
outH: layout.outH,
tmpPath: tmpPath ? 'ok' : 'empty',
}),
)
}, watchdogMs)
/** 与历史验证路径一致:临时 PNG → 解码光栅 → 下发。 */
printStage = 'raster-print-start'
showPrintInProgressDebugModal({
jobId: printJobId,
route: printRoute,
stage: printStage,
})
/** 以实际下发协议为准(内置+界面 TSC 时 resolveRasterPrintDriver 为 ESC,须走 ESC 分支与超时) */
if (rasterDriver.protocol === 'esc') {
await printImageForCurrentPrinter(
tmpPath,
{
printQty: printQty.value,
clearTopRasterRows: 0,
targetWidthDots: layout.outW,
targetHeightDots: layout.outH,
useContentHeight: true,
cutBetweenCopies: true,
},
(percent) => {
if (!isPrintJobActive(printJobId)) return
showPrintProgress(percent)
}
)
} else {
await withTimeout(printImageForCurrentPrinter(
tmpPath,
{
printQty: printQty.value,
clearTopRasterRows: 1,
targetWidthDots: layout.outW,
targetHeightDots: layout.outH,
labelRasterFixedHeight: true,
},
(percent) => {
if (!isPrintJobActive(printJobId)) return
showPrintProgress(percent)
}
), genericRasterJobMs, 'PRINT_TIMEOUT')
}
printStage = 'raster-print-done'
if (ENABLE_PRINT_RESULT_MODAL) await showPrintResultOnce()
}
}
}
}
/** 接口 9:仅本页业务标签出纸后落库(打印机设置/蓝牙 Test Print 不会执行此段) */
let printLogSyncFailed = false
let printLogRequestBody: ReturnType<typeof buildUsAppLabelPrintRequestBody> = null
if (!isPrintJobActive(printJobId)) {
console.warn('[preview] skip post-print API/preview refresh (stale job id)')
} else try {
const bt = getBluetoothConnection()
/**
* 接口 9 的 `printInputJson`:整份合并模板快照(与出纸 labelPrintJobPayload.template 同源)+
* buildPrintInputJson 的键值(PRINT_INPUT / 多选等),后端应原样落库并在接口 10 `renderTemplateJson` 返回供重打。
*/
const persistTemplateDoc = JSON.parse(
JSON.stringify(labelPrintJobPayload.template)
) as Record<string, unknown>
const printInputSnapshotForApi: Record<string, unknown> = {
...printInputJson,
...persistTemplateDoc,
}
printLogRequestBody = buildUsAppLabelPrintRequestBody({
locationId: getCurrentStoreId(),
labelCode: labelCode.value,
productId: productId.value || undefined,
printQuantity: printQty.value,
mergedTemplate: printInputSnapshotForApi,
clientRequestId: createPrintClientRequestId(),
printerMac: bt?.deviceId || undefined,
})
if (printLogRequestBody) {
await postUsAppLabelPrint(printLogRequestBody)
}
} catch (syncErr: unknown) {
if (String((syncErr as Error)?.message || '').includes('PRINT_JOB_STALE')) {
/* 用户极快连点打印时新任务已顶替,避免误 Toast / 二次 Loading */
} else if (!isUsAppSessionExpiredError(syncErr)) {
printLogSyncFailed = true
const msg = syncErr instanceof Error ? syncErr.message : String(syncErr)
console.error('[preview] 打印落库接口失败', {
接口说明: 'App 打印(落库打印任务与明细)',
接口路径: US_APP_LABEL_PRINT_PATH,
完整URL: buildApiUrl(US_APP_LABEL_PRINT_PATH),
方法: 'POST',
请求体: printLogRequestBody,
错误信息: msg,
原始错误: syncErr,
})
}
/** 401 时 usAppApiRequest 已 Toast + 跳转,此处不再处理 */
}
if (isPrintJobActive(printJobId)) {
const sz = getPreviewCanvasCssSize(tmpl, 720)
canvasCssW.value = sz.width
canvasCssH.value = sz.height
await waitForCanvasLayout()
try {
const path = await renderLabelPreviewToTempPath('labelPreviewCanvas', instance, tmpl, 720)
previewImageSrc.value = path
} catch {
/* 保持上一张预览图 */
}
}
uni.hideLoading()
if (isPrintJobActive(printJobId)) {
const qty = printQty.value
const printedTitle = `${qty} label${qty > 1 ? 's' : ''} printed!`
uni.showToast({
title: printLogSyncFailed ? `${printedTitle} (log not saved)` : printedTitle,
icon: printLogSyncFailed ? 'none' : 'success',
duration: printLogSyncFailed ? 2800 : 2000,
})
if (ENABLE_AUTO_NATIVE_DEBUG_MODAL && !printResultShown && shouldShowNativeFastDebugModal()) {
setTimeout(() => {
void showNativeFastPrinterDebugModal()
}, 450)
}
}
} catch (e: any) {
if (!isPrintJobActive(printJobId)) return
uni.hideLoading()
const msg = e?.message ? String(e.message) : 'Print failed'
/** withTimeout 触发的超时:不弹窗,仅日志(watchdog 已静默结束打印态) */
if (msg.includes('PRINT_TIMEOUT')) {
console.warn(
'[preview] print job timeout (promise)',
msg,
buildPrintDebugText({
stage: printStage,
route: printRoute,
jobId: printJobId,
elapsedMs: Date.now() - startedAt,
qty: printQty.value,
})
)
if (ENABLE_PRINT_RESULT_MODAL) {
await showPrintResultOnce()
} else {
uni.showToast({
title: 'Printing is taking longer, please wait…',
icon: 'none',
duration: 2500,
})
}
return
}
if (timeoutHandledByWatchdog) return
if (msg === 'BUILTIN_PLUGIN_NOT_FOUND' || (msg && msg.indexOf('Built-in printer') !== -1)) {
uni.showModal({
title: 'Built-in Print Not Available',
content:
'This device does not support TCP built-in printing. Please use Bluetooth: Printer Settings → connect your printer.',
confirmText: 'Printer Settings',
cancelText: 'Cancel',
success: (res) => {
if (res.confirm) uni.navigateTo({ url: '/pages/labels/bluetooth' })
if (shouldShowNativeFastDebugModal()) {
void showNativeFastPrinterDebugModal()
}
},
})
} else {
uni.showModal({
title: 'Print Failed',
content: `${msg}\n\n${buildPrintDebugText({
stage: printStage,
route: printRoute,
jobId: printJobId,
elapsedMs: Date.now() - startedAt,
qty: printQty.value,
})}`.trim(),
showCancel: false,
success: () => {
if (shouldShowNativeFastDebugModal()) {
void showNativeFastPrinterDebugModal()
}
},
})
}
} finally {
if (!isPrintJobActive(printJobId)) return
try {
uni.hideLoading()
} catch (_) {}
if (watchdog) clearTimeout(watchdog)
if (globalWatchdog) clearTimeout(globalWatchdog)
const t = systemTemplate.value
if (t && instance) {
const sz = getPreviewCanvasCssSize(t, 720)
canvasCssW.value = sz.width
canvasCssH.value = sz.height
}
if (!timeoutHandledByWatchdog) {
isPrinting.value = false
}
}
}
</script>
<style scoped>
.page {
min-height: 100vh;
background: #f9fafb;
overflow-x: hidden;
overflow-x: clip;
width: 100%;
max-width: 100vw;
box-sizing: border-box;
}
.header-hero {
background: linear-gradient(135deg, var(--theme-primary), var(--theme-primary-dark));
padding: 16rpx 32rpx 24rpx;
}
.top-bar {
height: 96rpx;
display: flex;
align-items: center;
justify-content: space-between;
}
.top-left,
.top-right {
width: 64rpx;
height: 64rpx;
border-radius: 999rpx;
background: rgba(255, 255, 255, 0.15);
display: flex;
align-items: center;
justify-content: center;
}
.top-center {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
}
.page-title {
font-size: 34rpx;
font-weight: 600;
color: #fff;
display: block;
}
.content {
padding: 32rpx;
padding-bottom: 300rpx;
box-sizing: border-box;
overflow-x: hidden;
overflow-x: clip;
width: 100%;
max-width: 100%;
min-width: 0;
}
.state-block {
padding: 80rpx 24rpx;
text-align: center;
}
.state-text {
font-size: 28rpx;
color: #6b7280;
}
.food-card {
background: #fff;
padding: 28rpx;
border-radius: 20rpx;
margin-bottom: 24rpx;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24rpx;
box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}
.food-info {
flex: 1;
min-width: 0;
}
.food-name {
font-size: 32rpx;
font-weight: 600;
color: #111827;
display: block;
margin-bottom: 4rpx;
}
.food-cat {
font-size: 26rpx;
color: #6b7280;
display: block;
}
.food-label-type {
display: flex;
align-items: center;
gap: 8rpx;
margin-top: 12rpx;
}
.food-label-type-text {
font-size: 24rpx;
color: var(--theme-primary);
font-weight: 500;
}
.food-template {
flex-shrink: 0;
text-align: center;
background: #f3f4f6;
padding: 16rpx 20rpx;
border-radius: 14rpx;
}
.template-size {
font-size: 28rpx;
font-weight: 700;
color: #111827;
display: block;
}
.template-name {
font-size: 22rpx;
color: #6b7280;
display: block;
margin-top: 4rpx;
}
.qty-card {
display: flex;
align-items: center;
justify-content: space-between;
background: #fff;
padding: 24rpx 28rpx;
border-radius: 20rpx;
margin-bottom: 32rpx;
box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}
.qty-label {
font-size: 30rpx;
font-weight: 600;
color: #111827;
}
.qty-control {
display: flex;
align-items: center;
}
.qty-btn {
width: 64rpx;
height: 64rpx;
border-radius: 14rpx;
background: #f3f4f6;
display: flex;
align-items: center;
justify-content: center;
}
.qty-btn:active {
background: #e5e7eb;
}
.qty-btn.disabled {
opacity: 0.35;
}
.qty-value {
width: 88rpx;
text-align: center;
font-size: 36rpx;
font-weight: 700;
color: #111827;
}
.print-options-card {
background: #fff;
border-radius: 20rpx;
padding: 28rpx;
margin-bottom: 28rpx;
box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}
.print-options-title {
font-size: 30rpx;
font-weight: 600;
color: #111827;
display: block;
margin-bottom: 12rpx;
}
.print-options-hint {
font-size: 24rpx;
color: #6b7280;
line-height: 1.45;
display: block;
margin-bottom: 24rpx;
}
.print-option-block {
margin-bottom: 28rpx;
}
.print-option-block:last-child {
margin-bottom: 0;
}
.print-option-label {
font-size: 26rpx;
font-weight: 600;
color: #374151;
display: block;
margin-bottom: 16rpx;
}
.chip-row {
display: flex;
flex-wrap: wrap;
gap: 22rpx;
}
.chip {
padding: 12rpx 24rpx;
border-radius: 999rpx;
background: #f3f4f6;
border: 2rpx solid #e5e7eb;
}
.chip-on {
background: #eff6ff;
border-color: var(--theme-primary);
}
.chip-text {
font-size: 24rpx;
color: #374151;
}
.chip-on .chip-text {
color: var(--theme-primary);
font-weight: 600;
}
.free-field-input {
width: 100%;
box-sizing: border-box;
height: 80rpx;
padding: 0 24rpx;
font-size: 28rpx;
color: #111827;
background: #f9fafb;
border: 2rpx solid #e5e7eb;
border-radius: 12rpx;
}
.picker-input {
display: flex;
align-items: center;
}
.picker-dialog-mask {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.45);
z-index: 2000;
display: flex;
align-items: center;
justify-content: center;
padding: 24rpx;
}
.picker-dialog {
width: 100%;
max-width: 680rpx;
background: #fff;
border-radius: 20rpx;
overflow: hidden;
}
.picker-dialog--wide {
max-width: 720rpx;
}
.picker-dialog-title {
font-size: 30rpx;
font-weight: 600;
color: #111827;
text-align: center;
padding: 20rpx 24rpx 8rpx;
}
.picker-view-box {
width: 100%;
height: 420rpx;
}
.picker-view-box--wide .picker-item {
font-size: 24rpx;
padding: 0 6rpx;
}
.picker-item {
height: 72rpx;
min-height: 72rpx;
max-height: 72rpx;
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center;
line-height: 1;
text-align: center;
font-size: 30rpx;
font-variant-numeric: tabular-nums;
color: #111827;
}
.picker-dialog-actions {
display: flex;
border-top: 1rpx solid #e5e7eb;
}
.picker-btn {
flex: 1;
height: 88rpx;
line-height: 88rpx;
text-align: center;
font-size: 30rpx;
}
.picker-btn-cancel {
color: #6b7280;
border-right: 1rpx solid #e5e7eb;
}
.picker-btn-confirm {
color: var(--theme-primary);
font-weight: 600;
}
.section-title {
font-size: 30rpx;
font-weight: 600;
color: #111827;
display: block;
margin-bottom: 20rpx;
}
.label-card {
background: #fff;
border-radius: 20rpx;
overflow: hidden;
overflow-x: clip;
margin-bottom: 24rpx;
box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
padding: 24rpx 0;
display: block;
width: 100%;
max-width: 100%;
position: relative;
}
.label-img-wrap {
width: 100%;
max-width: 100%;
overflow: hidden;
overflow-x: clip;
box-sizing: border-box;
position: relative;
}
.label-img {
width: 100%;
max-width: 100%;
height: auto;
display: block;
vertical-align: top;
object-fit: contain;
border-radius: 12rpx;
box-sizing: border-box;
}
.label-placeholder {
padding: 80rpx 24rpx;
text-align: center;
background: #f3f4f6;
border-radius: 12rpx;
}
.label-placeholder-text {
font-size: 26rpx;
color: #9ca3af;
}
.info-row {
display: flex;
margin-bottom: 24rpx;
}
.info-item {
flex: 1;
min-width: 0;
background: #fff;
padding: 20rpx 24rpx;
border-radius: 16rpx;
box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}
.info-item + .info-item {
margin-left: 10rpx;
}
.info-label {
font-size: 22rpx;
color: #9ca3af;
display: block;
margin-bottom: 6rpx;
}
.info-value {
font-size: 26rpx;
font-weight: 600;
color: #111827;
display: block;
}
.note-card {
display: flex;
align-items: flex-start;
gap: 16rpx;
padding: 24rpx 28rpx;
background: #eff6ff;
border: 1rpx solid #bfdbfe;
border-radius: 16rpx;
}
.note-text {
flex: 1;
font-size: 26rpx;
color: #1e40af;
line-height: 1.5;
}
.bottom-bar {
position: fixed;
bottom: 0;
left: 0;
right: 0;
padding: 20rpx 32rpx;
padding-bottom: calc(env(safe-area-inset-bottom, 0px) + 36px);
background: #fff;
border-top: 1rpx solid #e5e7eb;
box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.04);
}
.bottom-info {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16rpx;
}
.bottom-qty {
font-size: 26rpx;
font-weight: 600;
color: #111827;
}
.bt-indicator {
display: flex;
align-items: center;
gap: 8rpx;
}
.bt-dot {
width: 12rpx;
height: 12rpx;
border-radius: 50%;
background: #d1d5db;
}
.bt-indicator.connected .bt-dot {
background: #4ade80;
}
.bt-name {
font-size: 24rpx;
color: #9ca3af;
}
.bt-indicator.connected .bt-name {
color: #16a34a;
}
.bottom-actions {
display: flex;
align-items: stretch;
gap: 24rpx;
}
.btn-preview-sq {
width: 100rpx;
height: 100rpx;
flex-shrink: 0;
background: #fff;
border: 2rpx solid #d1d5db;
border-radius: 16rpx;
display: flex;
align-items: center;
justify-content: center;
}
.btn-preview-sq:active {
background: #f3f4f6;
}
.print-btn {
flex: 1;
min-width: 0;
height: 100rpx;
background: var(--theme-primary);
border-radius: 16rpx;
display: flex;
align-items: center;
justify-content: center;
gap: 12rpx;
}
.print-btn.disabled {
opacity: 0.6;
}
.print-btn-text {
font-size: 30rpx;
font-weight: 600;
color: #fff;
line-height: 1;
}
.hidden-canvas {
position: fixed;
left: -9999px;
top: 0;
opacity: 0;
pointer-events: none;
}
.modal-mask {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 999;
padding: 24rpx;
}
.modal-body {
width: 100%;
max-width: 700rpx;
max-height: 85vh;
background: #fff;
border-radius: 24rpx;
overflow-x: hidden;
overflow-y: auto;
display: flex;
flex-direction: column;
min-width: 0;
-webkit-overflow-scrolling: touch;
}
.modal-body-label-only .modal-label-wrap {
margin-bottom: 0;
padding: 24rpx;
}
.modal-label-id {
margin-top: 20rpx;
padding-top: 20rpx;
border-top: 1rpx solid #e5e7eb;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16rpx;
}
.modal-label-id-label {
font-size: 26rpx;
color: #6b7280;
font-weight: 500;
}
.modal-label-id-value {
font-size: 28rpx;
color: #111827;
font-weight: 600;
}
.modal-label-wrap {
width: 100%;
max-width: 100%;
margin-bottom: 24rpx;
padding: 0;
box-sizing: border-box;
overflow: visible;
}
.modal-label-inner {
width: 100%;
max-width: 100%;
min-width: 0;
overflow: hidden;
overflow-x: clip;
box-sizing: border-box;
}
.modal-label-img {
width: 100%;
max-width: 100%;
height: auto;
display: block;
vertical-align: top;
object-fit: contain;
border-radius: 12rpx;
box-sizing: border-box;
}
@media screen and (max-width: 768px) {
.page,
.content,
.label-card,
.label-img-wrap {
max-width: 100vw;
}
.label-img,
.modal-label-img {
max-width: 100% !important;
}
}
</style>