lefengyang
3 days ago ae667df60092e883cb92f92f092ff878a2360107
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
<template>
    <view class="page_bg">
        
        <uv-navbar :title="titleName" :autoBack="true" :placeholder="true" leftIconColor="#fff" bgColor="rgba(0,0,0,0)" titleStyle="color:#fff"></uv-navbar>
        
        <view class="temp">
            <view class="temp_item">
                <view class="title">
                    模版名称
                </view>
                <view class="item">
                    <uv-input placeholder="请输入名称" border="none" v-model="tempName" fontSize="27rpx"
                        customStyle="background: #ECEFF6;padding:18rpx 20rpx;border-radius: 10rpx;"></uv-input>
                </view>
            </view>
            <view class="temp_item">
                <view class="title">
                    封面图片
                </view>
                <view class="item item_pic">
                    <uv-upload :fileList="fileList1" name="1" :maxCount="1" width="200rpx" height="200rpx"
                        :previewFullImage="false" @afterRead="afterRead" @delete="deletePic">
                        <!-- <image v-if="fileList1.length != 0"
                            :src="baseURL + fileList1[0]?.url" 
                            mode="aspectFill" 
                            style="width: 200rpx;height: 200rpx;"
                        ></image>
                        <view class="item_pic_btn" v-else>
                            <uv-icon name="camera-fill" color="#ccc" size="60rpx"></uv-icon>
                        </view> -->
                    </uv-upload>
                </view>
            </view>
            <view class="temp_item" v-if="!isEditMode">
                <view class="title">
                    预制动画
                </view>
                <view class="item">
                    <uv-radio-group v-model="selectedPreset" placement="column" @change="changePreset" labelSize="26rpx">
                        <uv-radio
                            class="spec_radio"
                            v-for="(item, index) in presetList"
                            :key="index"
                            :label="'预制动画:'+item.name+'('+item.fpsTotal+'帧)'"
                            :name="item.name">
                        </uv-radio>
                    </uv-radio-group>
                </view>
            </view>
            <view class="temp_item">
                <view class="title">
                    屏幕规格
                </view>
                <view class="item">
                    <uv-radio-group v-model="specVal" placement="column" @change="changeSpec" labelSize="26rpx">
                        <uv-radio class="spec_radio" v-for="(item, index) in specList" :key="index" :label="item.name"
                            :name="item.name">
                        </uv-radio>
                    </uv-radio-group>
                </view>
            </view>
            <view class="temp_item">
                <view class="title">
                    动画方式
                </view>
                <view class="item">
                    <uv-radio-group v-model="modeVal" placement="column" @change="changeMode" labelSize="26rpx">
                        <uv-radio class="spec_radio" v-for="(item, index) in modeList" :key="index" :label="item.name"
                            :name="item.val">
                        </uv-radio>
                    </uv-radio-group>
                </view>
            </view>
 
            <view class="temp_item">
                <view class="title">
                    动画帧数
                </view>
                <view class="item" @click="clickTotal">
                    <uv-input placeholder="请输入" readonly border="none" v-model="total" suffixIcon="arrow-right"
                        suffixIconStyle="color: #bbb" fontSize="26rpx"
                        customStyle="background: #ECEFF6;padding:18rpx 20rpx;border-radius: 10rpx;"></uv-input>
                </view>
            </view>
            <view class="temp_item">
                <view class="title">
                    动画速度
                </view>
                <view class="item" @click="clickSpeed">
                    <uv-input placeholder="请输入" readonly border="none" v-model="speed" suffixIcon="arrow-right"
                        suffixIconStyle="color: #bbb" fontSize="26rpx"
                        customStyle="background: #ECEFF6;padding:18rpx 20rpx;border-radius: 10rpx;"></uv-input>
                </view>
            </view>
            <!-- <view class="temp_item" v-if="modeVal == 1">
                <view class="title">
                    循环次数
                </view>
                <view class="item">
                    <uv-input placeholder="请输入" readonly border="none" v-model="cycle" suffixIcon="arrow-right"
                        suffixIconStyle="color: #bbb" fontSize="26rpx" customStyle="background: #ECEFF6;padding:18rpx 20rpx;border-radius: 10rpx;"></uv-input>
                </view>
            </view> -->
            <view class="temp_item1" v-for="(item,index) in total" :key="index">
                <view class="title">
                    动画第{{item}}帧
                </view>
                <view class="item">
                    <uv-button text="编辑" @click="popupAnimationOpen(index)" shape="circle" size="small" color="linear-gradient( 142deg, #6FD2FF 0%, #268DFF 100%)"></uv-button>
                    <uv-button text="复制" @click="copyFrame(index)" shape="circle" size="small" color="linear-gradient( 142deg, #FFB347 0%, #FF8C00 100%)"></uv-button>
                </view>
            </view>
        </view>
 
        <view class="footer_none"></view>
        <view class="footer_btn">
            <uv-button text="预览" color="linear-gradient( 142deg, #6FD2FF 0%, #268DFF 100%)" shape="circle" customStyle="width:40vw;" @click="openPreview"></uv-button>
            <uv-button text="保存" color="linear-gradient( 142deg, #6FD2FF 0%, #268DFF 100%)" shape="circle" customStyle="width:40vw;" @click="clickTempleteAdd()"></uv-button>
        </view>
 
        <!-- 预览浮层 -->
        <view class="preview_overlay" v-if="previewShow" @click.self="closePreview">
            <view class="preview_title">预览动画</view>
            <view class="preview_matrix">
                <view class="preview_grid" :style="{
                    gridTemplateRows: 'repeat(' + previewHeight + ', auto)',
                    gridTemplateColumns: 'repeat(' + previewWidth + ', auto)'
                }">
                    <view class="preview_cell" v-for="(cell, idx) in currentPreviewFrame" :key="idx" :style="{ backgroundColor: cell || '#1a1a1a' }"></view>
                </view>
            </view>
            <view class="preview_close_btn" @click="closePreview">关闭</view>
        </view>
 
        <!-- 动画帧数 -->
        <uv-picker ref="pickerTotal" :columns="columnsTotal" @confirm="confirmTotal"></uv-picker>
 
        <!-- 动画速度 -->
        <uv-picker ref="pickerSpeed" :columns="columnsSpeed" @confirm="confirmSpeed"></uv-picker>
        
        <!-- 动画弹出框 -->
        <uv-popup ref="popupAnimation" mode="center" @change="changeAnimation" :safeAreaInsetTop="false" :safeAreaInsetBottom="false" :zoom="false" duration="0">
            <view class="animation_pixel">
                <view class="back_btn" v-show="false" @click="popupAnimationClose">
                    <uv-icon name="arrow-leftward" color="#333" size="30"></uv-icon>
                </view>
                <!-- 主操作按钮(收回/操作) - 移动模式下隐藏 -->
                <view class="controls" style="left: 30rpx;" v-if="!showMoveControls && !showMultiMoveControls">
                    <uv-button type="success" :plain="true" :text="showControls ? '收回' : '操作'" @click="toggleControls"></uv-button>
                </view>
 
                <!-- 主操作按钮组:颜色、移动、文字、清除、保存 -->
                <view class="controls" v-if="showControls && !showMoveControls && !showMultiMoveControls">
                    <uv-button type="primary" :plain="true" text="颜色" @click="changeColor()"></uv-button>
                    <uv-button type="primary" :plain="true" text="单帧移动" @click="enterMoveMode()"></uv-button>
                    <uv-button type="primary" :plain="true" text="多帧移动" @click="enterMultiMoveMode()"></uv-button>
                    <uv-button type="primary" :plain="true" text="文字" @click="addText()"></uv-button>
                    <uv-button type="primary" :plain="true" text="清除" @click="clear()"></uv-button>
                    <uv-button type="primary" :plain="true" text="保存" @click="clickSaveData"></uv-button>
                </view>
 
                <!-- 单帧移动按钮组:返回、左移、上移、下移、右移、180度旋转、左右镜像翻转、上下镜像翻转 -->
                <view class="controls" style="left: 30rpx;" v-if="showMoveControls">
                    <uv-button type="primary" :plain="true" text="返回" @click="exitMoveMode()"></uv-button>
                </view>
                <view class="controls move_controls" v-if="showMoveControls">
                    <uv-button type="primary" :plain="true" text="左移" @click="shiftLeft()"></uv-button>
                    <uv-button type="primary" :plain="true" text="上移" @click="shiftUp()"></uv-button>
                    <uv-button type="primary" :plain="true" text="下移" @click="shiftDown()"></uv-button>
                    <uv-button type="primary" :plain="true" text="右移" @click="shiftRight()"></uv-button>
                    <uv-button type="primary" :plain="true" text="180°旋转" @click="rotate180()"></uv-button>
                    <uv-button type="primary" :plain="true" text="左右镜像" @click="flipHorizontal()"></uv-button>
                    <uv-button type="primary" :plain="true" text="上下镜像" @click="flipVertical()"></uv-button>
                </view>
 
                <!-- 多帧移动按钮组:操作对所有帧生效 -->
                <view class="controls" style="left: 30rpx;" v-if="showMultiMoveControls">
                    <uv-button type="primary" :plain="true" text="返回" @click="exitMultiMoveMode()"></uv-button>
                </view>
                <view class="controls move_controls" v-if="showMultiMoveControls">
                    <uv-button type="primary" :plain="true" text="左移" @click="multiShiftLeft()"></uv-button>
                    <uv-button type="primary" :plain="true" text="上移" @click="multiShiftUp()"></uv-button>
                    <uv-button type="primary" :plain="true" text="下移" @click="multiShiftDown()"></uv-button>
                    <uv-button type="primary" :plain="true" text="右移" @click="multiShiftRight()"></uv-button>
                    <uv-button type="primary" :plain="true" text="180°旋转" @click="multiRotate180()"></uv-button>
                    <uv-button type="primary" :plain="true" text="左右镜像" @click="multiFlipHorizontal()"></uv-button>
                    <uv-button type="primary" :plain="true" text="上下镜像" @click="multiFlipVertical()"></uv-button>
                </view>
                
                <!-- 文字生成图形 -->
                <canvas canvas-id="myCanvas" id="myCanvas" class="canvas" :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"></canvas>
                <!-- canvasWidth:{{ canvasWidth }} | canvasHeight:{{ canvasHeight }} -->
 
                <!-- 点阵图 -->
                <scroll-view scroll-x @scroll="handleScroll">
                    <view
                        class="pixel_grid"
                        @touchstart.prevent="handleTouchStart"
                        @touchmove.prevent="handleTouchMove"
                        @touchend.prevent="handleTouchEnd"
                        @touchcancel.prevent="handleTouchEnd"
                        :style="{
                            gridTemplateRows: `repeat(${height}, 1fr)`,
                            gridTemplateColumns: `repeat(${width * (modeVal == 2 ? 10 : 1)}, 1fr)`,
                            width: modeVal == 2 ? '1000vw': '100vw',
                        }">
                        <view class="pixel_cell" v-for="(cell, cellIndex) in pixelData" :key="cellIndex">
                            <view class="pixel_cell_item" :style="{ backgroundColor: cell }"></view>
                        </view>
                    </view>
                    <view style="height:20vh;"></view>
                </scroll-view>
                <view class="exit_btn">
                    <uv-button type="success" :plain="true" text="退出" @click="popupAnimationClose"></uv-button>
                </view>
            </view>
        </uv-popup>
        
        <!-- 分辨率 -->
        <uv-picker ref="pickerRatio" :columns="columnsRatio" @confirm="confirmRatio"></uv-picker>
        
        <!-- 颜色选择器 -->
        <uv-popup ref="pickerColor" mode="bottom" round="10" :closeable="true">
            <scroll-view scroll-y :show-scrollbar="false" class="color-picker-scroll">
                <view class="color-picker-wrapper">
                    <view class="color-picker-inner">
                        <x-color-picker
                            v-model="color"
                            :show-alpha="false"
                            :save-history="true"
                            :options="pickerOptions"
                            @confirm="onColorConfirm"
                            @cancel="onColorCancel" />
                    </view>
                </view>
            </scroll-view>
        </uv-popup>
        
        <!-- 添加文字弹窗 -->
        <uv-popup ref="popupText" mode="center" round="10" :safeAreaInsetTop="false" :safeAreaInsetBottom="false" :zoom="false" duration="0">
            <view class="text_popup">
                <view class="text_popup_title">添加文字</view>
                <view class="text_popup_item">
                    <view class="text_popup_label">文字</view>
                    <view class="text_popup_input">
                        <uv-input placeholder="请输入文字" border="none" v-model="tempText" fontSize="16px"
                            customStyle="background: #ECEFF6;padding:8px 10px;border-radius: 6px;"></uv-input>
                    </view>
                </view>
                <view class="text_popup_item">
                    <view class="text_popup_label">类型</view>
                    <view class="text_popup_type">
                        <uv-radio-group v-model="textType" placement="row" labelSize="16px" style="gap:10px;">
                            <uv-radio label="覆盖" name="overwrite"></uv-radio>
                            <uv-radio label="追加" name="append"></uv-radio>
                        </uv-radio-group>
                    </view>
                </view>
                <view class="text_popup_btn">
                    <uv-button type="info" text="取消" @click="closeTextPopup"></uv-button>
                    <uv-button type="primary" text="确定" @click="confirmAddText" customStyle=""></uv-button>
                </view>
            </view>
        </uv-popup>
        
    </view>
</template>
 
<script>
    import {
        templeteAdd,
        templeteInfo,
        templeteEdit,
        templeteList
    } from '@/api/api.js'
    let ctx = null
    export default {
        data() {
            return {
                tempName: '',
                pic: '',
                specList: [{
                    name: '12*24'
                }, {
                    name: '16*24'
                }, {
                    name: '18*24'
                }],
                specVal: '12*24',
                specWidth: 24,
                specHeight: 12,
                modeList: [{
                        name: '单个动画帧',
                        val: 0
                    },
                    {
                        name: '动画帧切换',
                        val: 1
                    },
                    {
                        name: '滚动动画',
                        val: 2
                    }
                ],
                modeVal: 0,
                columnsTotal: [
                    [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
                    ]
                ],
                total: 1, //动画总帧数
                columnsSpeed: [
                    [10, 20, 30, 40, 50, 60, 70, 80, 90]
                ],
                speed: 10,
                cycle: 1,
                fpsData: [],
                fpsIndex: 1, //第几帧
                fpsIds: [],
 
                baseURL: '',
                fileList1: [],
                animationData: [],
                fpsTotal: 1,
                
                
                
                // 模版动画
                pixelData: [],
                canvasData: [],
                canvasWidth: 240,
                canvasHeight: 120,
                width: 24,
                height: 12,
                color: '#FF0000',
                gridRect: null, // 存储像素网格的位置信息
                lastCell: null, // 防止重复绘制
                columnsRatio: [
                    ['12*24', '16*32', '24*48', '32*64', '40*80']
                ],
                // columnsRatio: [
                //  ['12*24']
                // ],
                color: '#FF0000',
                gridRect: null,
                pickerOptions: {
                    width: 680,
                },
                fpsList: [],
                tId: '',
                tempInfo:{},
                titleName: '新增模版',
                previewShow: false,
                previewFrames: [],
                previewFrameIndex: 0,
                previewTimer: null,
                previewWidth: 24,
                previewHeight: 12,
                showControls: false,
        showMoveControls: false, // 单帧移动模式按钮组开关
        showMultiMoveControls: false, // 多帧移动模式按钮组开关
            scrollLeft: 0,
                textType: 'overwrite',
                tempText: '',
                presetList: [],
                selectedPreset: '',
                isEditMode: false,
            }
        },
        computed: {
            currentPreviewFrame() {
                if (this.previewFrames.length === 0) return [];
                const frame = this.previewFrames[this.previewFrameIndex % this.previewFrames.length];
                return frame || [];
            }
        },
        onLoad(opt) {
            this.baseURL = uni.$uv.http.config.baseURL
            if(opt.id){
                this.tId = opt.id
                this.getTempleteInfo()
                this.titleName = '编辑模版'
                this.isEditMode = true
            }
            else{
                this.titleName = '新增模版'
                this.isEditMode = false
                this.getPresetList()
            }
        },
        onShow() {
            
        },
        onHide() {
            this.$refs.popupAnimation.close();
            this.stopPreviewAnimation();
            if (typeof plus !== 'undefined') {
                plus.screen.lockOrientation('portrait')
            }
        },
        onUnload() {
            this.stopPreviewAnimation();
            if (typeof plus !== 'undefined') {
                plus.screen.lockOrientation('portrait')
            }
        },
        methods: {
            getPresetList() {
                templeteList({
                    userId: 1,
                    pageNum: 1,
                    pageSize: 99
                }).then(res => {
                    console.log('预制动画列表-------', res.rows)
                    if(res.code == 200){
                        this.presetList = res.rows || []
                    }
                })
            },
            changePreset(val) {
                const preset = this.presetList.find(item => item.name === val)
                if (preset) {
                    this.specVal = preset.screen
                    this.modeVal = preset.mode
                    this.total = preset.fpsTotal
                    this.speed = preset.speed
                    if (preset.fpsList) {
                        this.fpsList = JSON.parse(preset.fpsList)
                    }
                }
            },
            handleScroll(e){
                this.scrollLeft = e.detail.scrollLeft
            },
            // 获取编辑详情
            getTempleteInfo(){
                templeteInfo(this.tId).then(res=>{
                    console.log('获取编辑详情-------',res)
                    if(res.code == 200){
                        this.tempInfo = res.data
                        this.tempName = this.tempInfo.name
                        this.fileList1.push({
                            url: this.baseURL + this.tempInfo.pic
                        })
                        
                        this.specVal = this.tempInfo.screen
                        this.modeVal = this.tempInfo.mode
                        
                        this.total = this.tempInfo.cycle
                        this.fpsTotal = this.tempInfo.fpsTotal
                        this.speed = this.tempInfo.speed
                        
                        this.fpsList = JSON.parse(this.tempInfo.fpsList)
                        
                    }
                    else{
                        uni.showToast({
                            title: res.msg,
                            duration: 2000,
                            icon: 'none'
                        });
                    }
                })
            },
            // 添加模版提交接口
            clickTempleteAdd() {
                
                if (!this.tempName) {
                    uni.showToast({
                        title: '请输入模版名称',
                        duration: 2000,
                        icon: 'none'
                    });
                    return
                }
                if (this.fileList1.length == 0) {
                    uni.showToast({
                        title: '请上传封面图片',
                        duration: 2000,
                        icon: 'none'
                    });
                    return
                }
                
                if (this.fpsList.length == 0) {
                    uni.showToast({
                        title: '请编辑动画帧',
                        duration: 2000,
                        icon: 'none'
                    });
                    return
                } else {
                    for (let i = 0; i < this.fpsList.length; i++) {
                        if (this.fpsList[i] === null) {
                            uni.showToast({
                                title: `请编辑第 ${i+1} 个动画帧`,
                                duration: 2000,
                                icon: 'none'
                            });
                            return
                        }
                    }
                }
                console.log('this.fpsList=========',this.fpsList)
                
                uni.showLoading({
                    title: '添加中',
                    mask: true
                });
                
                
                // 遍历二维数组
                this.fpsData = this.fpsList.map(inner =>
                  inner.map(item => {
                    if (item === "") {
                      return "000000"; // 空的改成000000
                    } else if (item.includes("#")) {
                      return item.replace("#", ""); // 去掉#
                    } else {
                      return item; // 保持原样
                    }
                  })
                );
                
                console.log('this.fpsData=========',this.fpsData)
                
                // 动画方式
                if (this.modeVal == 0) { //一帧动画
                    let frames = this.generateFrames(this.fpsData[0], 24);
                    const parsedData = frames.map(item => {
                        return this.toSnakeData(item, this.specWidth)
                    });
                    this.animationData = parsedData.map(item => {
                        return this.mergeRowsToString(item)
                    });
                    this.fpsTotal = 24
                } else if (this.modeVal == 1) {
                    console.log('modeVal--------1')
                    const parsedData = this.fpsData.map(item => {
                        return this.toSnakeData(item, this.specWidth)
                    });
                    console.log('modeVal--------1',parsedData)
                    this.animationData = parsedData.map(item => {
                        return this.mergeRowsToString(item)
                    });
                    this.fpsTotal = this.total
                } else if (this.modeVal == 2) {
                    const scrollFrames = this.generateScrollFrames(this.fpsData[0]);
                    const parsedData = scrollFrames.map(item => {
                        return this.toSnakeData(item, this.specWidth);
                    });
                    this.animationData = parsedData.map(item => {
                        return this.mergeRowsToString(item);
                    });
                    this.fpsTotal = scrollFrames.length;
                }
                console.log('animationData--------', this.animationData)
                
                // 判断this.fileList1[0].url里是否有 this.baseURL
                if (this.fileList1[0].url.includes(this.baseURL)) {
                    this.fileList1[0].url = this.fileList1[0].url.replace(this.baseURL, "");
                }
                
                console.log('url----',this.fileList1[0].url);
                
                // 判断如果有id就编辑
                if(this.tId){
                    const putData = {
                        id: this.tId,
                        name: this.tempName,
                        userId: uni.getStorageSync('userId'),
                        screen: this.specVal, //屏幕
                        mode: this.modeVal,
                        cycle: this.total,
                        fpsTotal: this.fpsTotal, //总帧数
                        speed: this.speed, //速度
                        pic: this.fileList1[0].url,
                        fpsData: JSON.stringify(this.animationData),
                        fpsList: JSON.stringify(this.fpsList)
                    }
                    console.log('putData-----', putData)
                    templeteEdit(putData).then(res => {
                        console.log('编辑动画模版', res)
                        uni.hideLoading();
                        if (res.code == 200) {
                            uni.navigateBack({
                                delta: 1
                            });
                        } else {
                            uni.showToast({
                                title: res.msg,
                                duration: 1500,
                                icon: 'none',
                                mask: true
                            });
                        }
                    })
                }
                else{
                    const addData = {
                        name: this.tempName,
                        userId: uni.getStorageSync('userId'),
                        screen: this.specVal, //屏幕
                        mode: this.modeVal,
                        cycle: this.total,
                        fpsTotal: this.fpsTotal, //总帧数
                        speed: this.speed, //速度
                        pic: this.fileList1[0].url,
                        fpsData: JSON.stringify(this.animationData),
                        fpsList: JSON.stringify(this.fpsList)
                    }
                    console.log('addData-----', addData)
                    templeteAdd(addData).then(res => {
                        console.log('添加动画模版', res)
                        uni.hideLoading();
                        if (res.code == 200) {
                            uni.navigateBack({
                                delta: 1
                            });
                        } else {
                            uni.showToast({
                                title: res.msg,
                                duration: 1500,
                                icon: 'none',
                                mask: true
                            });
                        }
                    })
                }
                
            },
            // 保存动画
            clickSaveData() {
                this.fpsList[this.fpsIndex] = this.pixelData;
                this.$refs.popupAnimation.close();
            },
            changeColor() {
                this.$refs.pickerColor.open();
            },
            onColorConfirm(colorObj) {
                this.color = colorObj.hex;
                this.$refs.pickerColor.close();
            },
            onColorCancel() {
                this.$refs.pickerColor.close();
            },
            changeRatio() {
                this.$refs.pickerRatio.open();
            },
            // 分辨率
            confirmRatio(e) {
                console.log('confirmRatio---', e.value[0]);
                const ratio = e.value[0].split('*');
                console.log('ratio---', ratio[0]);
                this.height = Number(ratio[0]);
                this.width = Number(ratio[1]);
                this.canvasWidth = this.width * (this.modeVal == 2 ? 10 * 10 : 10);
                this.canvasHeight = this.height * 10;
                const colCount = this.width * (this.modeVal == 2 ? 10 : 1)
                this.pixelData = new Array(this.height * colCount).fill('')
                console.log('pixelData---', this.pixelData);
            },
            // 预先获取像素网格的位置信息
            getGridRect(cb) {
                if (this.gridRect) {
                    cb(this.gridRect)
                } else {
                    uni.createSelectorQuery().in(this).select('.pixel_grid').boundingClientRect(rect => {
                        this.gridRect = rect
                        cb(rect)
                    }).exec()
                }
            },
            // 计算触摸点对应的格子
            getCellByTouch(touch, cb) {
                this.getGridRect(rect => {
                    if (!rect) return
                    const x = touch.clientX + this.scrollLeft
                    const y = touch.clientY - rect.top
                    const colCount = this.width * (this.modeVal == 2 ? 10 : 1)
                    const cellWidth = rect.width / colCount
                    const cellHeight = rect.height / this.height
                    const colIndex = Math.floor(x / cellWidth)
                    const rowIndex = Math.floor(y / cellHeight)
                    //console.log('colCount', colCount, 'rowIndex', rowIndex, 'colIndex', colIndex, x, cellWidth)
                    if (
                        colIndex >= 0 && colIndex < colCount &&
                        rowIndex >= 0 && rowIndex < this.height
                    ) {
                        cb({
                            rowIndex,
                            colIndex
                        })
                    }
                })
            },
            handleTouchStart(e) {
                // 阻止默认行为
                e.preventDefault && e.preventDefault();
            
                if (!e.touches.length) return
                this.getCellByTouch(e.touches[0], cell => {
                    this.lastCell = cell
                    this.handleClick(cell.rowIndex, cell.colIndex)
                })
            },
            handleTouchMove(e) {
                // 阻止默认行为
                e.preventDefault && e.preventDefault();
            
                if (!e.touches.length) return
                this.getCellByTouch(e.touches[0], cell => {
                    // 只在格子变化时才触发
                    if (!this.lastCell || this.lastCell.rowIndex !== cell.rowIndex || this.lastCell.colIndex !==
                        cell.colIndex) {
                        this.lastCell = cell
                        this.handleClick(cell.rowIndex, cell.colIndex)
                    }
                })
            },
            handleTouchEnd() {
                this.lastCell = null
            },
            handleClick(rowIndex, colIndex) {
                console.log(rowIndex, colIndex)
                // 计算一维数组的索引
                const colCount = this.width * (this.modeVal == 2 ? 10 : 1)
                const index = rowIndex * colCount + colIndex
                // 如果当前像素有颜色,则清除;如果没有颜色,则添加当前选择的颜色
                const currentColor = this.pixelData[index]
                const newColor = currentColor ? '' : this.color
                this.$set(this.pixelData, index, newColor)
            },
            clear() {
                ctx && ctx.clearRect(0, 0, 1000, 1000)
                const colCount = this.width * (this.modeVal == 2 ? 10 : 1)
                // 将所有像素点设置为空字符串
                this.pixelData = new Array(this.height * colCount).fill('')
            },
            shiftLeft() {
                const colCount = this.width * (this.modeVal == 2 ? 10 : 1)
                for (let r = 0; r < this.height; r++) {
                    const rowStart = r * colCount
                    const row = this.pixelData.slice(rowStart, rowStart + colCount)
                    const shifted = row.slice(1).concat(row.slice(0, 1))
                    for (let c = 0; c < colCount; c++) {
                        this.$set(this.pixelData, rowStart + c, shifted[c])
                    }
                }
            },
            shiftRight() {
                const colCount = this.width * (this.modeVal == 2 ? 10 : 1)
                for (let r = 0; r < this.height; r++) {
                    const rowStart = r * colCount
                    const row = this.pixelData.slice(rowStart, rowStart + colCount)
                    const shifted = row.slice(colCount - 1).concat(row.slice(0, colCount - 1))
                    for (let c = 0; c < colCount; c++) {
                        this.$set(this.pixelData, rowStart + c, shifted[c])
                    }
                }
            },
            shiftDown() {
                const colCount = this.width * (this.modeVal == 2 ? 10 : 1)
                const lastRowStart = (this.height - 1) * colCount
                const lastRow = this.pixelData.slice(lastRowStart, lastRowStart + colCount)
                for (let r = this.height - 1; r > 0; r--) {
                    const currentStart = r * colCount
                    const prevStart = (r - 1) * colCount
                    for (let c = 0; c < colCount; c++) {
                        this.$set(this.pixelData, currentStart + c, this.pixelData[prevStart + c])
                    }
                }
                for (let c = 0; c < colCount; c++) {
                    this.$set(this.pixelData, c, lastRow[c])
                }
            },
            // 上移一像素:整体内容上移,首行补到末行
            shiftUp() {
                const colCount = this.width * (this.modeVal == 2 ? 10 : 1)
                const firstRow = this.pixelData.slice(0, colCount)
                for (let r = 0; r < this.height - 1; r++) {
                    const currentStart = r * colCount
                    const nextStart = (r + 1) * colCount
                    for (let c = 0; c < colCount; c++) {
                        this.$set(this.pixelData, currentStart + c, this.pixelData[nextStart + c])
                    }
                }
                const lastRowStart = (this.height - 1) * colCount
                for (let c = 0; c < colCount; c++) {
                    this.$set(this.pixelData, lastRowStart + c, firstRow[c])
                }
            },
            // 180度旋转:整体一维数组反转即可实现180度旋转
            rotate180() {
                this.pixelData = this.pixelData.slice().reverse()
            },
            // 左右镜像翻转:每行内部反转
            flipHorizontal() {
                const colCount = this.width * (this.modeVal == 2 ? 10 : 1)
                const newData = this.pixelData.slice()
                for (let r = 0; r < this.height; r++) {
                    const rowStart = r * colCount
                    const reversedRow = newData.slice(rowStart, rowStart + colCount).reverse()
                    for (let c = 0; c < colCount; c++) {
                        newData[rowStart + c] = reversedRow[c]
                    }
                }
                this.pixelData = newData
            },
            // 上下镜像翻转:行顺序反转
            flipVertical() {
                const colCount = this.width * (this.modeVal == 2 ? 10 : 1)
                let newData = []
                for (let r = this.height - 1; r >= 0; r--) {
                    const rowStart = r * colCount
                    newData = newData.concat(this.pixelData.slice(rowStart, rowStart + colCount))
                }
                this.pixelData = newData
            },
            // 进入移动模式:隐藏主按钮组,显示移动按钮组
            enterMoveMode() {
                this.showMoveControls = true
                this.showMultiMoveControls = false
                this.showControls = false
            },
            // 退出移动模式:恢复主按钮组
            exitMoveMode() {
                this.showMoveControls = false
                this.showControls = true
            },
            // 进入多帧移动模式:隐藏主按钮组,显示多帧移动按钮组
            enterMultiMoveMode() {
                this.showMultiMoveControls = true
                this.showMoveControls = false
                this.showControls = false
            },
            // 退出多帧移动模式:恢复主按钮组
            exitMultiMoveMode() {
                this.showMultiMoveControls = false
                this.showControls = true
            },
            // 对所有已编辑帧执行同一种单帧变换
            // action: 单帧变换方法名(shiftLeft/shiftUp/shiftDown/shiftRight/rotate180/flipHorizontal/flipVertical)
            applyTransformToAllFrames(action) {
                const currentIndex = this.fpsIndex
                // 以编辑区当前显示的数据(可能包含未保存的修改)作为当前帧的数据源
                let currentData = this.pixelData ? this.pixelData.slice() : this.pixelData
                for (let i = 0; i < this.fpsList.length; i++) {
                    if (i === currentIndex) continue
                    const frame = this.fpsList[i]
                    if (frame === null || frame === undefined) continue
                    // 复用单帧变换逻辑:临时把该帧作为编辑数据执行变换后写回
                    this.pixelData = frame.slice()
                    this[action]()
                    this.$set(this.fpsList, i, this.pixelData.slice())
                }
                // 对当前正在编辑的帧执行相同变换,刷新画布显示
                this.pixelData = currentData.slice()
                this[action]()
                // 当前帧此前已保存过则同步写回,保证所有帧数据一致;未编辑过的帧(null)仍由"保存"按钮写入
                const stored = this.fpsList[currentIndex]
                if (stored !== null && stored !== undefined) {
                    this.$set(this.fpsList, currentIndex, this.pixelData.slice())
                }
            },
            // 多帧移动:所有帧同时左移
            multiShiftLeft() {
                this.applyTransformToAllFrames('shiftLeft')
            },
            // 多帧移动:所有帧同时上移
            multiShiftUp() {
                this.applyTransformToAllFrames('shiftUp')
            },
            // 多帧移动:所有帧同时下移
            multiShiftDown() {
                this.applyTransformToAllFrames('shiftDown')
            },
            // 多帧移动:所有帧同时右移
            multiShiftRight() {
                this.applyTransformToAllFrames('shiftRight')
            },
            // 多帧移动:所有帧同时180度旋转
            multiRotate180() {
                this.applyTransformToAllFrames('rotate180')
            },
            // 多帧移动:所有帧同时左右镜像
            multiFlipHorizontal() {
                this.applyTransformToAllFrames('flipHorizontal')
            },
            // 多帧移动:所有帧同时上下镜像
            multiFlipVertical() {
                this.applyTransformToAllFrames('flipVertical')
            },
            toggleControls() {
                this.showControls = !this.showControls;
            },
            // 模版动画弹出框
            changeAnimation(e){
                //console.log('打开关闭模版动画弹窗触发---',e)
                // ios设备不支持弹出框横屏切换
                if(e.show){
                    if (typeof plus !== 'undefined') {
                        plus.screen.lockOrientation('landscape-primary')
                    }
                }
                else{
                    if (typeof plus !== 'undefined') {
                        plus.screen.lockOrientation('portrait-primary')
                    }
                }
            },
            // 打开模版动画
            popupAnimationOpen(index){
                this.$refs.popupAnimation.open();
                this.fpsIndex = index
                this.canvasWidth = this.width * (this.modeVal == 2 ? 10 * 10 : 10);
                
                if(this.fpsList[this.fpsIndex] == null){
                    console.log('第一次编辑-----null')
                    let pointCount = this.height * this.width
                    if (this.modeVal == 2) {
                        pointCount *= 10
                    }
                    this.pixelData = new Array(pointCount).fill('')
                }else{
                    console.log('已编辑过-----')
                    this.pixelData = this.fpsList[this.fpsIndex]
                }
            },
            // 关闭模版动画
            popupAnimationClose(){
                this.$refs.popupAnimation.close();
                const colCount = this.width * (this.modeVal == 2 ? 10 : 1)
                this.pixelData = new Array(this.height * colCount).fill('')
                // 重置按钮组状态,下次打开回到主操作界面
                this.showMoveControls = false
                this.showMultiMoveControls = false
                this.showControls = false
            },
            // 复制当前帧
            copyFrame(index) {
                uni.showModal({
                    title: '提示',
                    content: '确定要复制当前帧吗?',
                    success: (res) => {
                        if (res.confirm) {
                            const source = this.fpsList[index];
                            const copy = source ? [...source] : null;
                            this.fpsList.splice(index + 1, 0, copy);
                            this.total = this.fpsList.length;
                            uni.showToast({
                                title: '复制成功',
                                icon: 'success',
                                duration: 1500
                            });
                        }
                    }
                });
            },
            // 屏幕规格
            changeSpec(e) {
                const ratio = e.split('*');
                this.specHeight = Number(ratio[0]);
                this.specWidth = Number(ratio[1]);
            },
            // 偶数行数据反转
            toSnakeData(pixelData, cols = 24) {
                const rows = []
                for (let i = 0; i < pixelData.length; i += cols) {
                    let row = pixelData.slice(i, i + cols)
                    if ((rows.length + 1) % 2 === 0) {
                        row.reverse() // 偶数行反转
                    }
                    rows.push(row)
                }
                return rows
            },
            // 二维数组转字符串
            mergeRowsToString(rows) {
                const rowStrings = rows.map(r => r.join('')) // 每行合并
                return rowStrings.join('') // 所有行合并
            },
            // 生成滚动动画帧数据(modeVal==2)
            // 从点阵图左侧开始,按照设定分辨率窗口提取动画帧,每帧左移3个像素,剩余全空时停止
            generateScrollFrames(data) {
                const cols = this.specWidth;
                const rows = this.specHeight;
                const totalCols = this.specWidth * 10;
                const step = 3;
 
                let grid = [];
                for (let r = 0; r < rows; r++) {
                    grid.push(data.slice(r * totalCols, (r + 1) * totalCols));
                }
 
                const frames = [];
                let offset = 0;
 
                while (offset < totalCols) {
                    let remainingEmpty = true;
                    for (let r = 0; r < rows; r++) {
                        for (let c = offset; c < totalCols; c++) {
                            if (grid[r][c] !== '' && grid[r][c] !== '000000') {
                                remainingEmpty = false;
                                break;
                            }
                        }
                        if (!remainingEmpty) break;
                    }
 
                    if (remainingEmpty) break;
 
                    let frame = [];
                    for (let r = 0; r < rows; r++) {
                        let row = grid[r].slice(offset, offset + cols);
                        while (row.length < cols) {
                            row.push('000000');
                        }
                        frame = frame.concat(row);
                    }
 
                    frames.push(frame);
                    offset += step;
                }
 
                return frames;
            },
            // 生成一帧动画其他帧数据
            generateFrames(data, frameCount = 24) {
                const cols = this.specWidth; // 每行 24 个
                const rows = this.specHeight; // 共 12 行
                const frames = [];
                // 拆分成 12 行
                let grid = [];
                for (let r = 0; r < rows; r++) {
                    grid.push(data.slice(r * cols, (r + 1) * cols));
                }
                // 生成帧
                for (let f = 0; f < frameCount; f++) {
                    let frame = [];
                    // 每行左移 f 次
                    for (let r = 0; r < rows; r++) {
                        let row = grid[r].slice(); // 拷贝一行
                        let shifted = row.slice(f % cols).concat(row.slice(0, f % cols));
                        frame = frame.concat(shifted);
                    }
                    frames.push(frame);
                }
                return frames;
            },
            
            clickSpeed() {
                this.$refs.pickerSpeed.open();
            },
            confirmSpeed(e) {
                console.log('confirmSpeed', e.value[0]);
                this.speed = e.value[0]
            },
            clickTotal() {
                if (this.total != 1) {
                    this.$refs.pickerTotal.open();
                }
            },
            confirmTotal(e) {
                console.log('confirmTotal', e.value[0]);
                this.total = e.value[0]
                this.adjustFpsData()
            },
            changeMode(e) {
                this.fpsList = []
                this.fpsData = []
                this.gridRect = null
                if (e == 0 || e == 2) {
                    this.total = 1
                } else {
                    this.total = 2
                }
                this.adjustFpsData()
            },
            adjustFpsData() {
                // 如果 fpsData 太长 → 截取
                if (this.fpsList.length > this.total) {
                    this.fpsList = this.fpsList.slice(0, this.total);
                }
                // 如果 fpsData 太短 → 补齐 null
                else if (this.fpsList.length < this.total) {
                    const missing = this.total - this.fpsList.length;
                    this.fpsList = this.fpsList.concat(new Array(missing).fill(null));
                }
                
                // 如果 fpsList 太长 → 截取
                if (this.fpsData.length > this.total) {
                    this.fpsData = this.fpsData.slice(0, this.total);
                }
                // 如果 fpsList 太短 → 补齐 null
                else if (this.fpsData.length < this.total) {
                    const missing = this.total - this.fpsData.length;
                    this.fpsData = this.fpsData.concat(new Array(missing).fill(null));
                }
            },
            // 删除图片
            deletePic(event) {
                this[`fileList${event.name}`].splice(event.index, 1)
            },
            // 新增图片
            async afterRead(event) {
                console.log('event---', event)
                // 当设置 multiple 为 true 时, file 为数组格式,否则为对象格式
                let lists = [].concat(event.file)
                let fileListLen = this[`fileList${event.name}`].length
                lists.map((item) => {
                    this[`fileList${event.name}`].push({
                        ...item,
                        status: 'uploading',
                        message: '上传中'
                    })
                })
                for (let i = 0; i < lists.length; i++) {
                    const result = await this.uploadFilePromise(lists[i].url)
                    this.avatar = result
                    let item = this[`fileList${event.name}`][fileListLen]
                    this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
                        status: 'success',
                        message: '',
                        url: result
                    }))
                    fileListLen++
                }
            },
            uploadFilePromise(url) {
                return new Promise((resolve, reject) => {
                    let a = uni.uploadFile({
                        url: this.baseURL + '/common/uploadFileByAnny', // 仅为示例,非真实的接口地址
                        filePath: url,
                        name: 'file',
                        success: (res) => {
                            console.log('图片-----', JSON.parse(res.data))
                            setTimeout(() => {
                                resolve(JSON.parse(res.data).fileName)
                            }, 1000)
                        }
                    });
                })
            },
            // 生成点阵数据
            generateDotMatrix(char, startCol = null) {
                return new Promise((resolve, reject) => {
            
                    // 使用 uni-app 的 canvas context
                    ctx = uni.createCanvasContext('myCanvas', this);
            
                    // 设置字体样式
                    ctx.setFontSize(this.canvasHeight);
                    ctx.setFillStyle('#000')
                    ctx.setTextBaseline('middle')
                    // 绘制文字
                    // 垂直居中,稍微向上偏移一点
                    const y = this.canvasHeight / 2 + 10;
                    const colCount = this.width * (this.modeVal == 2 ? 10 : 1)
                    
                    if (startCol !== null) {
                        ctx.setTextAlign('left')
                        const cellWidth = this.canvasWidth / colCount;
                        const x = startCol * cellWidth;
                        ctx.fillText(char, x, y);
                    } else if (this.modeVal == 2) {
                        // 滚动动画:文字靠左对齐
                        ctx.setTextAlign('left')
                        const x = 20;
                        ctx.fillText(char, x, y);
                    } else {
                        // 其他模式:文字水平居中
                        ctx.setTextAlign('center')
                        const x = this.canvasWidth / 2;
                        ctx.fillText(char, x, y);
                    }
            
                    // 绘制到画布
                    ctx.draw(false, () => {
                        // 获取画布数据
                        uni.canvasGetImageData({
                            canvasId: 'myCanvas',
                            x: 0,
                            y: 0,
                            width: this.canvasWidth,
                            height: this.canvasHeight,
                            success: (res) => {
                                console.log('canvasGetImageData', res)
                                const imageData = res.data;
                                // 生成一维数组
                                const colCount = this.width * (this.modeVal == 2 ? 10 : 1)
                                const pixelArray = new Array(this.height * colCount).fill('')
 
                                // 计算每个格子的像素大小
                                const cellWidth = this.canvasWidth / colCount;
                                const cellHeight = this.canvasHeight / this.height;
            
                                // 生成一维数组
                                for (let y = 0; y < this.height; y++) {
                                    for (let x = 0; x < colCount; x++) {
                                        let blackPixels = 0;
                                        let totalPixels = 0;
            
                                        // 对每个格子进行采样
                                        for (let py = 0; py < cellHeight; py++) {
                                            for (let px = 0; px < cellWidth; px++) {
                                                const pixelY = Math.floor(y * cellHeight + py);
                                                const pixelX = Math.floor(x * cellWidth + px);
            
                                                const idx = (pixelY * this.canvasWidth + pixelX) * 4;
                                                const r = imageData[idx];
                                                const g = imageData[idx + 1];
                                                const b = imageData[idx + 2];
                                                const a = imageData[idx + 3];
            
                                                // 计算亮度
                                                const brightness = 0.3 * r + 0.59 * g + 0.11 * b;
 
                                                // 如果亮度小于阈值且透明度大于阈值,则认为是黑色
                                                if (brightness < 128 && a > 128) {
                                                    blackPixels++;
                                                }
                                                totalPixels++;
                                            }
                                        }
 
                                        // 如果黑色像素占比超过阈值,则设置为当前选择的颜色
                                        const isBlack = blackPixels / totalPixels > 0.3;
                                        const arrayIndex = y * colCount + x;
                                        pixelArray[arrayIndex] = isBlack ? this.color : '';
                                    }
                                }
            
                                resolve(pixelArray);
                            },
                            fail: (err) => {
                                reject(err);
                            }
                        });
                    });
                });
            },
            
            openPreview() {
                if (this.fpsList.length === 0 || this.fpsList.every(f => f === null || f === undefined)) {
                    uni.showToast({
                        title: '请先编辑动画帧',
                        icon: 'none'
                    });
                    return;
                }
                this.previewWidth = this.modeVal == 2 ? this.specWidth : this.width;
                this.previewHeight = this.height;
                this.previewFrames = this.buildPreviewFrames();
                this.previewFrameIndex = 0;
                this.previewShow = true;
                this.$nextTick(() => {
                    this.startPreviewAnimation();
                });
            },
            closePreview() {
                this.stopPreviewAnimation();
                this.previewShow = false;
            },
            buildPreviewFrames() {
                if (this.modeVal == 0) {
                    const data = this.fpsList[0];
                    if (!data) return [];
                    return this.generatePreviewFrames(data, 24);
                } else if (this.modeVal == 2) {
                    const data = this.fpsList[0];
                    if (!data) return [];
                    return this.generateScrollFrames(data);
                } else {
                    const frames = [];
                    for (let i = 0; i < this.total; i++) {
                        if (this.fpsList[i] && this.fpsList[i] !== null) {
                            frames.push(this.fpsList[i]);
                        } else {
                            frames.push(new Array(this.width * this.height).fill(''));
                        }
                    }
                    return frames;
                }
            },
            generatePreviewFrames(data, frameCount) {
                const cols = this.width;
                const rows = this.height;
                const frames = [];
                let grid = [];
                for (let r = 0; r < rows; r++) {
                    grid.push(data.slice(r * cols, (r + 1) * cols));
                }
                for (let f = 0; f < frameCount; f++) {
                    let frame = [];
                    for (let r = 0; r < rows; r++) {
                        let row = grid[r].slice();
                        let shifted = row.slice(f % cols).concat(row.slice(0, f % cols));
                        frame = frame.concat(shifted);
                    }
                    frames.push(frame);
                }
                return frames;
            },
            startPreviewAnimation() {
                this.stopPreviewAnimation();
                if (!this.speed || this.speed <= 0 || this.previewFrames.length === 0) return;
                const interval = this.speed * 2.8;
                console.log('interval', interval)
                this.previewTimer = setInterval(() => {
                    this.previewFrameIndex = (this.previewFrameIndex + 1) % this.previewFrames.length;
                }, interval);
            },
            stopPreviewAnimation() {
                if (this.previewTimer) {
                    clearInterval(this.previewTimer);
                    this.previewTimer = null;
                }
            },
            addText() {
                this.tempText = '';
                this.textType = 'overwrite';
                this.$refs.popupText.open();
            },
            closeTextPopup() {
                this.$refs.popupText.close();
            },
            async confirmAddText() {
                const text = this.tempText;
                if (!text || text.length === 0) {
                    uni.showToast({
                        title: '请输入文字',
                        icon: 'none'
                    });
                    return;
                }
                
                try {
                    if (this.textType === 'overwrite') {
                        const dotMatrix = await this.generateDotMatrix(text);
                        this.pixelData = dotMatrix;
                    } else {
                        const colCount = this.width * (this.modeVal == 2 ? 10 : 1);
                        const rightmostCol = this.findRightmostNonEmptyCol(colCount);
                        const startCol = rightmostCol === -1 ? 0 : rightmostCol + 2;
                        const dotMatrix = await this.generateDotMatrix(text, startCol);
                        this.mergePixelData(dotMatrix);
                    }
                    this.$refs.popupText.close();
                } catch (error) {
                    console.error('生成点阵失败:', error);
                    uni.showToast({
                        title: '生成点阵失败',
                        icon: 'none'
                    });
                }
            },
            findRightmostNonEmptyCol(colCount) {
                for (let col = colCount - 1; col >= 0; col--) {
                    let isEmpty = true;
                    for (let row = 0; row < this.height; row++) {
                        const index = row * colCount + col;
                        if (this.pixelData[index] !== '' && this.pixelData[index] !== null && this.pixelData[index] !== undefined) {
                            isEmpty = false;
                            break;
                        }
                    }
                    if (!isEmpty) {
                        return col;
                    }
                }
                return -1;
            },
            mergePixelData(dotMatrix) {
                for (let i = 0; i < dotMatrix.length; i++) {
                    if (dotMatrix[i] !== '' && dotMatrix[i] !== null && dotMatrix[i] !== undefined) {
                        this.$set(this.pixelData, i, dotMatrix[i]);
                    }
                }
            },
        }
    }
</script>
 
<style lang="scss" scoped>
    page {
      -webkit-text-size-adjust: 100%;
      text-size-adjust: 100%;
    }
    .item_pic_btn{
        width: 200rpx;
        height: 200rpx;
        background: #eee;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 15rpx;
    }
    .color_picker_wrapper {
        padding: 30rpx 0;
        display: flex;
        justify-content: center;
    }
    .color-picker-scroll {
        max-height: 90vh;
        box-sizing: border-box;
    }
    .color-picker-wrapper {
        //zoom: 0.5;
    }
    
    .action_btn {
        position: absolute;
        bottom: 10px;
        left: 50px;
        z-index: 10;
        background: linear-gradient(142deg, #6FD2FF 0%, #268DFF 100%);
        padding: 12px 24px;
        border-radius: 30px;
        box-shadow: 0 4px 12px rgba(38, 141, 255, 0.4);
    }
    .controls {
        position: absolute;
        bottom: 10rpx;
        left: 100rpx;
        display: flex;
        gap: 10rpx;
        z-index: 9;
    }
    // 移动模式按钮组:8个按钮需要换行排列
    .move_controls {
        flex-wrap: wrap;
        justify-content: flex-start;
        max-width: calc(100vw - 200rpx);
        ::v-deep .uv-button {
            margin: 4rpx 0;
        }
    }
    .exit_btn{
        position: absolute;
        right: 30rpx;
        bottom: 10rpx;
        z-index: 9999;
    }
    .animation_pixel{
        width: 100vw;
        height: 100vh;
        position: relative;
        .back_btn{
            position: absolute;
            left: 30px;
            top: 20px;
            z-index: 9999;
        }
        .canvas {
            margin: 100rpx auto 0;
            background: #ccc;
            position: absolute;
            z-index: 1;
            left: -9999px;
            top: -9999px;
        }
        .pixel_grid {
            height: 80vh;
            border-bottom: 1px solid #eee;
            display: grid;
            gap: 1px;
            box-sizing: border-box;
            background: #eee;
            touch-action: none;
            -webkit-touch-callout: none;
            -webkit-user-select: none;
            user-select: none;
        
            .pixel_cell {
                display: flex;
                align-items: center;
                justify-content: center;
                box-sizing: border-box;
                background: #fff;
        
                .pixel_cell_item {
                    width: 50%;
                    height: 50%;
                    aspect-ratio: 1/1;
                    font-size: 10rpx;
                }
            }
        }
        
    }
    // -------------
    .footer_none {
        height: 200rpx;
    }
 
    .footer_btn {
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        background: #fff;
        padding: 30rpx 40rpx;
        display: flex;
        justify-content: space-between;
    }
 
    .preview_overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.85);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        z-index: 9999;
    }
    .preview_title {
        color: #fff;
        font-size: 34rpx;
        margin-bottom: 40rpx;
    }
    .preview_matrix {
        background: #000;
        padding: 20rpx;
        border-radius: 16rpx;
        box-shadow: 0 0 30rpx rgba(0, 150, 255, 0.3);
    }
    .preview_grid {
        display: grid;
        gap: 2rpx;
        background: #111;
        padding: 4rpx;
        border-radius: 8rpx;
    }
    .preview_cell {
        width: 22rpx;
        height: 22rpx;
        border-radius: 50%;
        background: #1a1a1a;
        box-shadow: inset 0 0 4rpx rgba(0, 0, 0, 0.5);
    }
    .preview_close_btn {
        margin-top: 60rpx;
        width: 300rpx;
        height: 80rpx;
        line-height: 80rpx;
        text-align: center;
        color: #fff;
        background: linear-gradient(142deg, #6FD2FF 0%, #268DFF 100%);
        border-radius: 40rpx;
        font-size: 30rpx;
    }
 
    .temp_btn {
        position: fixed;
        left: 30rpx;
        bottom: 60rpx;
        right: 30rpx;
        box-sizing: border-box;
        height: 96rpx;
        background: linear-gradient(142deg, #6FD2FF 0%, #268DFF 100%);
        border-radius: 385rpx 385rpx 385rpx 385rpx;
        font-size: 30rpx;
        color: #FFFFFF;
        line-height: 96rpx;
        text-align: center;
    }
 
    .spec_radio {
        margin-top: 30rpx;
 
        &:first-child {
            margin-top: 10rpx;
        }
    }
 
    .temp {
        padding: 0 30rpx;
 
        .temp_item1 {
            display: flex;
            align-items: center;
            justify-content: space-between;
            background: linear-gradient(180deg, #FFFFFF 0%, rgba(255, 255, 255, 0.5) 100%);
            box-shadow: 8rpx 8rpx 23rpx 0rpx rgba(67, 147, 248, 0.1), -8rpx -8rpx 23rpx 0rpx rgba(255, 255, 255, 0.4);
            border-radius: 23rpx 23rpx 23rpx 23rpx;
            border: 2rpx solid #FFFFFF;
            padding: 30rpx;
            box-sizing: border-box;
            margin-top: 24rpx;
 
            .title {
                flex-shrink: 0;
                font-size: 30rpx;
                color: rgba(0, 0, 0, 0.9);
                line-height: 40rpx;
 
            }
 
            .item {
                flex-direction:row;
                gap:20rpx;
                display:flex;
            }
        }
 
        .temp_item {
            display: flex;
            align-items: flex-start;
            justify-content: flex-start;
            flex-direction: column;
            background: linear-gradient(180deg, #FFFFFF 0%, rgba(255, 255, 255, 0.5) 100%);
            box-shadow: 8rpx 8rpx 23rpx 0rpx rgba(67, 147, 248, 0.1), -8rpx -8rpx 23rpx 0rpx rgba(255, 255, 255, 0.4);
            border-radius: 23rpx 23rpx 23rpx 23rpx;
            border: 2rpx solid #FFFFFF;
            padding: 30rpx;
            box-sizing: border-box;
            margin-top: 24rpx;
 
            .title {
                flex-shrink: 0;
                font-size: 30rpx;
                color: rgba(0, 0, 0, 0.9);
                line-height: 40rpx;
            }
 
            .item {
                margin-top: 20rpx;
                width: 100%;
                font-size: 30rpx;
                display: flex;
                flex-direction: column;
                &.item_pic {
                    margin-top: 25rpx;
                }
            }
        }
    }
 
    .page_bg {
        width: 100%;
        min-height: calc(100vh - var(--window-bottom));
        background: url('/static/img/bg_2.jpg') no-repeat center top;
        background-size: 100% auto;
    }
    
    .text_popup {
        width: 600rpx;
        background: #fff;
        border-radius: 20rpx;
        padding: 40rpx 30rpx;
        box-sizing: border-box;
        
        .text_popup_title {
            font-size: 16px;
            font-weight: bold;
            color: #333;
            text-align: center;
            margin-bottom: 15px;
        }
        
        .text_popup_item {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
            
            .text_popup_label {
                width: 50px;
                font-size: 16px;
                color: #666;
                flex-shrink: 0;
            }
            
            .text_popup_input {
                flex: 1;
                font-size: 16px;
            }
            
            .text_popup_type {
                flex: 1;
            }
        }
        
        .text_popup_btn {
            display: flex;
            margin-top: 20px;
            justify-content: center;
            gap: 20px;
        }
    }
</style>