wangrong
2026-08-30 761e5c5fa871959f60e15c971c8d83f2b53d0af5
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
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
/* eslint-disable prettier/prettier */
import {
  copyString,
  hexColorToRGBA,
  isAlphaColor,
  isTransparent,
  parseJson,
  resetRgbOpacity,
  safeDecimalSum,
  safeDecimalMean
} from '../..//util'
import {
  DEFAULT_BASIC_STYLE,
  DEFAULT_TABLE_CELL,
  DEFAULT_TABLE_HEADER
} from '@/views/chart/components/editor/util/chart'
import {
  BaseTooltip,
  DataCellBrushSelection,
  FONT_FAMILY,
  getAutoAdjustPosition,
  getEmptyPlaceholder,
  getPolygonPoints,
  getTooltipDefaultOptions,
  InteractionName,
  InteractionStateName,
  MergedCell,
  MergedCellInfo,
  type Meta,
  type Node,
  type PivotSheet,
  renderPolygon,
  renderText,
  S2DataConfig,
  S2Event,
  S2Options,
  S2Theme,
  SERIES_NUMBER_FIELD,
  EXTRA_FIELD,
  setTooltipContainerStyle,
  SHAPE_STYLE_MAP,
  SpreadSheet,
  Style,
  TableColCell,
  TableDataCell,
  updateShapeAttr,
  ViewMeta
} from '@antv/s2'
import {
  cloneDeep,
  filter,
  find,
  intersection,
  keys,
  map,
  maxBy,
  merge,
  minBy,
  repeat,
  isNumber
} from 'lodash-es'
import { createVNode, render } from 'vue'
import TableTooltip from '@/views/chart/components/editor/common/TableTooltip.vue'
import Exceljs from 'exceljs'
import { saveAs } from 'file-saver'
import { ElMessage } from 'element-plus-secondary'
import { useI18n } from '@/hooks/web/useI18n'
import Decimal from 'decimal.js'
 
const { t: i18nt } = useI18n()
 
export function getCustomTheme(chart: Chart): S2Theme {
  const headerColor = hexColorToRGBA(
    DEFAULT_TABLE_HEADER.tableHeaderBgColor,
    DEFAULT_BASIC_STYLE.alpha
  )
  const headerAlign = DEFAULT_TABLE_HEADER.tableHeaderAlign
  const itemColor = hexColorToRGBA(DEFAULT_TABLE_CELL.tableItemBgColor, DEFAULT_BASIC_STYLE.alpha)
  const itemAlign = DEFAULT_TABLE_CELL.tableItemAlign
  const borderColor = hexColorToRGBA(
    DEFAULT_BASIC_STYLE.tableBorderColor,
    DEFAULT_BASIC_STYLE.alpha
  )
  const scrollBarColor = DEFAULT_BASIC_STYLE.tableScrollBarColor
  const scrollBarHoverColor = resetRgbOpacity(scrollBarColor, 3)
  const textFontFamily =
    chart.fontFamily && chart.fontFamily !== 'inherit' ? chart.fontFamily : FONT_FAMILY
  const theme: S2Theme = {
    background: {
      color: '#00000000'
    },
    splitLine: {
      horizontalBorderColor: borderColor,
      horizontalBorderColorOpacity: 1,
      horizontalBorderWidth: 1,
      verticalBorderColor: borderColor,
      verticalBorderColorOpacity: 1,
      verticalBorderWidth: 1,
      showShadow: false
    },
    cornerCell: {
      cell: {
        backgroundColor: headerColor,
        horizontalBorderColor: borderColor,
        verticalBorderColor: borderColor
      },
      text: {
        fill: DEFAULT_TABLE_HEADER.tableHeaderFontColor,
        fontSize: DEFAULT_TABLE_HEADER.tableTitleFontSize,
        textAlign: headerAlign,
        fontFamily: textFontFamily
      },
      bolderText: {
        fill: DEFAULT_TABLE_HEADER.tableHeaderFontColor,
        fontSize: DEFAULT_TABLE_HEADER.tableTitleFontSize,
        textAlign: headerAlign,
        fontFamily: textFontFamily
      },
      measureText: {
        fill: DEFAULT_TABLE_HEADER.tableHeaderFontColor,
        fontSize: DEFAULT_TABLE_HEADER.tableTitleFontSize,
        textAlign: headerAlign,
        fontFamily: textFontFamily
      }
    },
    rowCell: {
      cell: {
        backgroundColor: headerColor,
        horizontalBorderColor: borderColor,
        verticalBorderColor: borderColor
      },
      text: {
        fill: DEFAULT_TABLE_HEADER.tableHeaderFontColor,
        fontSize: DEFAULT_TABLE_HEADER.tableTitleFontSize,
        textAlign: headerAlign,
        textBaseline: 'middle',
        fontFamily: textFontFamily
      },
      bolderText: {
        fill: DEFAULT_TABLE_HEADER.tableHeaderFontColor,
        fontSize: DEFAULT_TABLE_HEADER.tableTitleFontSize,
        textAlign: headerAlign,
        fontFamily: textFontFamily
      },
      measureText: {
        fill: DEFAULT_TABLE_HEADER.tableHeaderFontColor,
        fontSize: DEFAULT_TABLE_HEADER.tableTitleFontSize,
        textAlign: headerAlign,
        fontFamily: textFontFamily
      },
      seriesText: {
        fill: DEFAULT_TABLE_CELL.tableItemBgColor,
        fontSize: DEFAULT_TABLE_CELL.tableItemFontSize,
        textAlign: itemAlign,
        fontFamily: textFontFamily
      }
    },
    colCell: {
      cell: {
        backgroundColor: headerColor,
        horizontalBorderColor: borderColor,
        verticalBorderColor: borderColor
      },
      text: {
        fill: DEFAULT_TABLE_HEADER.tableHeaderFontColor,
        fontSize: DEFAULT_TABLE_HEADER.tableTitleFontSize,
        textAlign: headerAlign,
        fontFamily: textFontFamily
      },
      bolderText: {
        fill: DEFAULT_TABLE_HEADER.tableHeaderFontColor,
        fontSize: DEFAULT_TABLE_HEADER.tableTitleFontSize,
        textAlign: headerAlign,
        fontFamily: textFontFamily
      },
      measureText: {
        fill: DEFAULT_TABLE_HEADER.tableHeaderFontColor,
        fontSize: DEFAULT_TABLE_HEADER.tableTitleFontSize,
        textAlign: headerAlign,
        fontFamily: textFontFamily
      }
    },
    dataCell: {
      cell: {
        backgroundColor: itemColor,
        horizontalBorderColor: borderColor,
        verticalBorderColor: borderColor
      },
      text: {
        fill: DEFAULT_TABLE_CELL.tableFontColor,
        fontSize: DEFAULT_TABLE_CELL.tableItemFontSize,
        textAlign: itemAlign,
        fontFamily: textFontFamily
      },
      bolderText: {
        fill: DEFAULT_TABLE_CELL.tableFontColor,
        fontSize: DEFAULT_TABLE_CELL.tableItemFontSize,
        textAlign: itemAlign,
        fontFamily: textFontFamily
      },
      measureText: {
        fill: DEFAULT_TABLE_CELL.tableFontColor,
        fontSize: DEFAULT_TABLE_CELL.tableItemFontSize,
        textAlign: headerAlign,
        fontFamily: textFontFamily
      }
    },
    scrollBar: {
      thumbColor: scrollBarColor,
      thumbHoverColor: scrollBarHoverColor,
      size: 8,
      hoverSize: 12
    }
  }
 
  let customAttr: DeepPartial<ChartAttr>
  if (chart.customAttr) {
    customAttr = parseJson(chart.customAttr)
    const { basicStyle, tableHeader, tableCell } = customAttr
    // basic
    if (basicStyle) {
      const tableBorderColor = basicStyle.tableBorderColor
      const tableScrollBarColor = basicStyle.tableScrollBarColor
      const tmpTheme: S2Theme = {
        splitLine: {
          horizontalBorderColor: tableBorderColor,
          verticalBorderColor: tableBorderColor
        },
        cornerCell: {
          cell: {
            horizontalBorderColor: tableBorderColor,
            verticalBorderColor: tableBorderColor
          }
        },
        colCell: {
          cell: {
            horizontalBorderColor: tableBorderColor,
            verticalBorderColor: tableBorderColor
          }
        },
        dataCell: {
          cell: {
            horizontalBorderColor: tableBorderColor,
            verticalBorderColor: tableBorderColor,
            interactionState: {
              hoverFocus: {
                borderOpacity: basicStyle.showHoverStyle === false ? 0 : 1
              }
            }
          }
        },
        scrollBar: {
          thumbColor: tableScrollBarColor,
          thumbHoverColor: resetRgbOpacity(tableScrollBarColor, 1.5)
        }
      }
      merge(theme, tmpTheme)
    }
    // header
    if (tableHeader) {
      const tableHeaderFontColor = hexColorToRGBA(
        tableHeader.tableHeaderFontColor,
        basicStyle.alpha
      )
      let tableHeaderBgColor = tableHeader.tableHeaderBgColor
      if (!isAlphaColor(tableHeaderBgColor)) {
        tableHeaderBgColor = hexColorToRGBA(tableHeaderBgColor, basicStyle.alpha)
      }
      const fontStyle = tableHeader.isItalic ? 'italic' : 'normal'
      const fontWeight = tableHeader.isBolder === false ? 'normal' : 'bold'
      const { tableHeaderAlign, tableTitleFontSize } = tableHeader
      const tmpTheme: S2Theme = {
        cornerCell: {
          cell: {
            backgroundColor: tableHeaderBgColor
          },
          bolderText: {
            fill: tableHeaderFontColor,
            fontSize: tableTitleFontSize,
            textAlign: tableHeaderAlign,
            fontStyle,
            fontWeight,
            fontFamily: textFontFamily
          },
          text: {
            fill: tableHeaderFontColor,
            fontSize: tableTitleFontSize,
            textAlign: tableHeaderAlign,
            fontStyle,
            fontWeight,
            fontFamily: textFontFamily
          },
          measureText: {
            fill: tableHeaderFontColor,
            fontSize: tableTitleFontSize,
            textAlign: tableHeaderAlign,
            fontStyle,
            fontWeight,
            fontFamily: textFontFamily
          }
        },
        colCell: {
          cell: {
            backgroundColor: tableHeaderBgColor
          },
          bolderText: {
            fill: tableHeaderFontColor,
            fontSize: tableTitleFontSize,
            textAlign: tableHeaderAlign,
            fontStyle,
            fontWeight,
            fontFamily: textFontFamily
          },
          text: {
            fill: tableHeaderFontColor,
            fontSize: tableTitleFontSize,
            textAlign: tableHeaderAlign,
            fontStyle,
            fontWeight,
            fontFamily: textFontFamily
          },
          measureText: {
            fill: tableHeaderFontColor,
            fontSize: tableTitleFontSize,
            textAlign: tableHeaderAlign,
            fontStyle,
            fontWeight,
            fontFamily: textFontFamily
          }
        }
      }
      merge(theme, tmpTheme)
      // 这边设置为 0 的话就会显示表头背景颜色,所以要判断一下表头是否关闭
      if (tableHeader.showHorizonBorder === false && tableHeader.showTableHeader !== false) {
        const tmpTheme: S2Theme = {
          splitLine: {
            horizontalBorderColor: tableHeaderBgColor,
            horizontalBorderWidth: 0,
            horizontalBorderColorOpacity: 0
          },
          colCell: {
            cell: {
              horizontalBorderColor: tableHeaderBgColor,
              horizontalBorderWidth: 0
            }
          }
        }
        merge(theme, tmpTheme)
      }
      if (tableHeader.showVerticalBorder === false && tableHeader.showTableHeader !== false) {
        const tmpTheme: S2Theme = {
          splitLine: {
            verticalBorderColor: tableHeaderBgColor,
            verticalBorderWidth: 0,
            verticalBorderColorOpacity: 0
          },
          colCell: {
            cell: {
              verticalBorderColor: tableHeaderBgColor,
              verticalBorderWidth: 0
            }
          },
          cornerCell: {
            cell: {
              verticalBorderColor: tableHeaderBgColor,
              verticalBorderWidth: 0
            }
          }
        }
        merge(theme, tmpTheme)
      }
    }
    // cell
    if (tableCell) {
      const tableFontColor = hexColorToRGBA(tableCell.tableFontColor, basicStyle.alpha)
      let tableItemBgColor = tableCell.tableItemBgColor
      if (!isAlphaColor(tableItemBgColor)) {
        tableItemBgColor = hexColorToRGBA(tableItemBgColor, basicStyle.alpha)
      }
      let tableItemSubBgColor = tableCell.tableItemSubBgColor
      if (!isAlphaColor(tableItemSubBgColor)) {
        tableItemSubBgColor = hexColorToRGBA(tableItemSubBgColor, basicStyle.alpha)
      }
      const fontStyle = tableCell.isItalic ? 'italic' : 'normal'
      const fontWeight = tableCell.isBolder === false ? 'normal' : 'bold'
      const { tableItemAlign, tableItemFontSize, enableTableCrossBG } = tableCell
      const tmpTheme: S2Theme = {
        rowCell: {
          cell: {
            backgroundColor: tableItemBgColor,
            horizontalBorderColor: tableItemBgColor,
            verticalBorderColor: tableItemBgColor
          },
          bolderText: {
            fill: tableFontColor,
            textAlign: tableItemAlign,
            fontSize: tableItemFontSize,
            fontFamily: textFontFamily
          },
          text: {
            fill: tableFontColor,
            textAlign: tableItemAlign,
            fontSize: tableItemFontSize,
            fontFamily: textFontFamily
          },
          measureText: {
            fill: tableFontColor,
            textAlign: tableItemAlign,
            fontSize: tableItemFontSize,
            fontFamily: textFontFamily
          },
          seriesText: {
            fill: tableFontColor,
            textAlign: tableItemAlign,
            fontSize: tableItemFontSize,
            fontFamily: textFontFamily
          }
        },
        dataCell: {
          cell: {
            crossBackgroundColor: enableTableCrossBG ? tableItemSubBgColor : tableItemBgColor,
            backgroundColor: tableItemBgColor
          },
          bolderText: {
            fill: tableFontColor,
            textAlign: tableItemAlign,
            fontSize: tableItemFontSize,
            fontStyle,
            fontWeight,
            fontFamily: textFontFamily
          },
          text: {
            fill: tableFontColor,
            textAlign: tableItemAlign,
            fontSize: tableItemFontSize,
            fontStyle,
            fontWeight,
            fontFamily: textFontFamily
          },
          measureText: {
            fill: tableFontColor,
            textAlign: tableItemAlign,
            fontSize: tableItemFontSize,
            fontStyle,
            fontWeight,
            fontFamily: textFontFamily
          },
          seriesText: {
            fill: tableFontColor,
            textAlign: tableItemAlign,
            fontSize: tableItemFontSize,
            fontStyle,
            fontWeight,
            fontFamily: textFontFamily
          }
        }
      }
      merge(theme, tmpTheme)
      if (tableCell.showHorizonBorder === false) {
        const tmpTheme: S2Theme = {
          dataCell: {
            cell: {
              horizontalBorderColor: tableItemBgColor,
              horizontalBorderWidth: 0
            }
          }
        }
        merge(theme, tmpTheme)
      }
      if (tableCell.showVerticalBorder === false) {
        const tmpTheme: S2Theme = {
          splitLine: {
            verticalBorderWidth: 0,
            verticalBorderColorOpacity: 0
          },
          dataCell: {
            cell: {
              verticalBorderColor: tableItemBgColor,
              verticalBorderWidth: 0
            }
          }
        }
        merge(theme, tmpTheme)
      }
    }
  }
 
  return theme
}
 
export function getStyle(chart: Chart, dataConfig: S2DataConfig): Style {
  const style: Style = {}
  let customAttr: DeepPartial<ChartAttr>
  if (chart.customAttr) {
    customAttr = parseJson(chart.customAttr)
    const { basicStyle, tableHeader, tableCell } = customAttr
    style.colCfg = {
      height: tableHeader.tableTitleHeight
    }
    style.cellCfg = {
      height: tableCell.tableItemHeight
    }
    switch (basicStyle.tableColumnMode) {
      case 'adapt': {
        style.layoutWidthType = 'compact'
        break
      }
      case 'field': {
        delete style.layoutWidthType
        const fieldMap =
          basicStyle.tableFieldWidth?.reduce((p, n) => {
            p[n.fieldId] = n
            return p
          }, {}) || {}
        // 下钻字段使用入口字段的宽度
        if (chart.drill) {
          const { xAxis } = parseJson(chart)
          const curDrillField = chart.drillFields[chart.drillFilters.length]
          const drillEnterFieldIndex = xAxis.findIndex(
            item => item.id === chart.drillFilters[0].fieldId
          )
          const drillEnterField = xAxis[drillEnterFieldIndex]
          fieldMap[curDrillField.dataeaseName] = {
            width: fieldMap[drillEnterField.dataeaseName]?.width
          }
        }
        // 铺满
        const totalWidthPercent = dataConfig.meta?.reduce((p, n) => {
          return p + (fieldMap[n.field]?.width ?? 10)
        }, 0)
        const fullFilled = parseInt(totalWidthPercent.toFixed(0)) === 100
        const widthArr = []
        style.colCfg.width = node => {
          const width = node.spreadsheet.container.cfg.el.getBoundingClientRect().width
          if (!basicStyle.tableFieldWidth?.length) {
            const fieldsSize = chart.data.fields.length
            const columnCount = tableHeader.showIndex ? fieldsSize + 1 : fieldsSize
            return width / columnCount
          }
          const baseWidth = width / 100
          const tmpWidth = fieldMap[node.field]
            ? fieldMap[node.field].width * baseWidth
            : baseWidth * 10
          const resultWidth = parseInt(tmpWidth.toFixed(0))
          if (fullFilled) {
            if (widthArr.length === dataConfig.meta.length - 1) {
              const curTotalWidth = widthArr.reduce((p, n) => {
                return p + n
              }, 0)
              const restWidth = width - curTotalWidth
              widthArr.splice(0)
              if (restWidth < resultWidth) {
                return restWidth
              }
            } else {
              widthArr.push(resultWidth)
            }
          }
          return resultWidth
        }
        break
      }
      case 'custom': {
        style.colCfg.width = basicStyle.tableColumnWidth
        break
      }
      case 'colAdapt': {
        style.layoutWidthType = 'colAdaptive'
        const parentNodeWidthMap = {}
        const nodeMaxWidthMap = {}
        const quotaLabelMap = chart.yAxis?.reduce((p, n) => {
          p[n.dataeaseName] = n.chartShowName || n.name
          return p
        }, {}) || {}
        let calcCount = 50
        //只计算最后两层表头的宽度,采样 50 个数据
        style.colCfg.width = node => {
          const spreadsheet = node.spreadsheet
          const colHeaderTheme = spreadsheet.theme.colCell.bolderText
          const padding = spreadsheet.theme.colCell.cell.padding
          const paddingWidth = (padding?.left || 8) + (padding?.right || 8) + 12
          // 小计总计和第一层表头直接根据文本计算宽度
          if (node.isTotals || node.parent.id === 'root') {
            let label = node.label
            if (node.key === EXTRA_FIELD) {
              label = quotaLabelMap[node.label] || label
            }
            const totalsWidth = spreadsheet.measureTextWidth(label, colHeaderTheme) + paddingWidth
            return totalsWidth
          }
 
          const parentWidth = parentNodeWidthMap[node.parent.id]
          if (!parentWidth || (parentWidth && calcCount < 50)) {
            const parentLabel = node.parent.label
            const parentTextWidth = spreadsheet.measureTextWidth(parentLabel, colHeaderTheme) + paddingWidth
            parentNodeWidthMap[node.parent.id] = parentTextWidth
            const siblings = node.parent.children
            const siblingsTextWidthMap = {}
            const siblingsWidth = siblings.reduce((p, n) => {
              let label = n.label
              if (n.key === EXTRA_FIELD) {
                label = quotaLabelMap[n.label] || label
              }
              const pureTextWidth = spreadsheet.measureTextWidth(label, colHeaderTheme)
              if (n.key === EXTRA_FIELD) {
                siblingsTextWidthMap[n.label] = pureTextWidth
              }
              calcCount++
              return p + pureTextWidth + paddingWidth
            }, 0)
            if (siblingsWidth < parentTextWidth) {
              const offsetWidth = parentTextWidth - siblingsWidth
              const expandOffsetWidth = offsetWidth / Object.keys(siblingsTextWidthMap).length
              for (const key in siblingsTextWidthMap) {
                const tmpWidth = siblingsTextWidthMap[key] + Math.ceil(expandOffsetWidth) + paddingWidth
                const maxWidth = nodeMaxWidthMap[key]
                if (!maxWidth || (maxWidth && tmpWidth > maxWidth)) {
                  nodeMaxWidthMap[key] = tmpWidth
                }
              }
            } else {
              for (const key in siblingsTextWidthMap) {
                const tmpWidth = siblingsTextWidthMap[key] + paddingWidth
                const maxWidth = nodeMaxWidthMap[key]
                if (!maxWidth || (maxWidth && tmpWidth > maxWidth)) {
                  nodeMaxWidthMap[key] = tmpWidth
                }
              }
            }
            return nodeMaxWidthMap[node.label]
          } else {
            const fieldWidth = nodeMaxWidthMap[node.label]
            if (fieldWidth) {
              return fieldWidth
            }
            const textWidth = spreadsheet.measureTextWidth(node.label, colHeaderTheme) + paddingWidth
            return textWidth
          }
        }
        break
      }
      // 查看详情用,均分铺满
      default: {
        delete style.layoutWidthType
        style.colCfg.width = node => {
          const width = node.spreadsheet.container.cfg.el.offsetWidth
          const fieldsSize = node.spreadsheet.dataCfg.meta.length
          if (!fieldsSize) {
            return 0
          }
          const columnCount = tableHeader.showIndex ? fieldsSize + 1 : fieldsSize
          const minWidth = width / columnCount
          return Math.max(minWidth, basicStyle.tableColumnWidth)
        }
      }
    }
  }
 
  return style
}
 
export function getCurrentField(valueFieldList: Axis[], field: ChartViewField) {
  let list = []
  let res = null
  try {
    list = parseJson(valueFieldList)
  } catch (err) {
    list = JSON.parse(JSON.stringify(valueFieldList))
  }
  if (list) {
    for (let i = 0; i < list.length; i++) {
      const f = list[i]
      if (field.dataeaseName === f.dataeaseName) {
        res = f
        break
      }
    }
  }
 
  return res
}
 
export function getConditions(chart: Chart) {
  const { threshold } = parseJson(chart.senior)
  if (!threshold.enable) {
    return
  }
  const res = {
    text: [],
    background: []
  }
  const conditions = threshold.tableThreshold ?? []
 
  const allFields = [...chart.xAxis]
  if (chart.type === 'table-normal') {
    allFields.push(...chart.yAxis)
  }
  const fieldIdToName = allFields.reduce((acc, f) => {
    acc[f.id] = f.dataeaseName
    return acc
  }, {})
  const allColumnNames = allFields.map(f => f.dataeaseName)
 
  if (conditions?.length > 0) {
    const { tableCell, basicStyle, tableHeader } = parseJson(chart.customAttr)
    // 合并单元格时斑马纹失效
    const enableTableCrossBG =
      chart.type === 'table-info'
        ? tableCell.enableTableCrossBG && !tableCell.mergeCells
        : tableCell.enableTableCrossBG
    const valueColor = isAlphaColor(tableCell.tableFontColor)
      ? tableCell.tableFontColor
      : hexColorToRGBA(tableCell.tableFontColor, basicStyle.alpha)
    const valueBgColor = enableTableCrossBG
      ? null
      : isAlphaColor(tableCell.tableItemBgColor)
      ? tableCell.tableItemBgColor
      : hexColorToRGBA(tableCell.tableItemBgColor, basicStyle.alpha)
    const filedValueMap = getFieldValueMap(chart)
 
    const targetRulesMap = {} // columnName -> Array<{ rule, sourceField }>
 
    for (let i = 0; i < conditions.length; i++) {
      const fieldItem = conditions[i]
      if (!fieldItem.conditions) continue;
 
      for (let j = 0; j < fieldItem.conditions.length; j++) {
        const rule = fieldItem.conditions[j]
        let targets = []
        if (rule.target === 'total_row') {
          targets = [...allColumnNames]
          // 明细表和汇总表需要包含序号列
          if (tableHeader.showIndex) {
            targets.push(SERIES_NUMBER_FIELD)
          }
        } else if (rule.target === 'custom' && rule.targetFieldId) {
          const targetName = fieldIdToName[rule.targetFieldId]
          if (targetName) targets = [targetName]
        } else {
          targets = [fieldItem.field.dataeaseName]
        }
 
        targets.forEach(targetName => {
          if (!targetRulesMap[targetName]) {
            targetRulesMap[targetName] = []
          }
          targetRulesMap[targetName].push({
            rule: rule,
            sourceField: fieldItem.field
          })
        })
      }
    }
 
    for (const targetName in targetRulesMap) {
      const rules = targetRulesMap[targetName]
      const defaultValueColor = valueColor
      const defaultBgColor = valueBgColor
 
      res.text.push({
        field: targetName,
        mapping(value, rowData) {
          if (!value && !rowData) {
            return null
          }
 
          return {
            fill: mappingColor(value, defaultValueColor, rules, 'color', filedValueMap, rowData)
          }
        }
      })
      res.background.push({
        field: targetName,
        mapping(value, rowData) {
          if (!value && !rowData) {
            return null
          }
          const fill = mappingColor(
            value,
            defaultBgColor,
            rules,
            'backgroundColor',
            filedValueMap,
            rowData
          )
          if (isTransparent(fill)) {
            return null
          }
          return { fill }
        }
      })
    }
  }
  return res
}
 
export function mappingColorCustom(value, defaultColor, field, type, filedValueMap?, rowData?) {
  let color = null
  for (let i = 0; i < field.conditions.length; i++) {
    let flag = false
    const t = field.conditions[i]
    let tv, max, min
    if (t.type === 'dynamic') {
      if (t.term === 'between') {
        max = parseFloat(getValue(t.dynamicMaxField, filedValueMap, rowData))
        min = parseFloat(getValue(t.dynamicMinField, filedValueMap, rowData))
      } else {
        tv = getValue(t.dynamicField, filedValueMap, rowData)
      }
    } else {
      if (t.term === 'between') {
        min = parseFloat(t.min)
        max = parseFloat(t.max)
      } else {
        tv = t.value
      }
    }
    if (field.field.deType === 2 || field.field.deType === 3 || field.field.deType === 4) {
      tv = parseFloat(tv)
      if (t.term === 'eq') {
        if (value === tv) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'not_eq') {
        if (value !== tv) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'lt') {
        if (value < tv) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'gt') {
        if (value > tv) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'le') {
        if (value !== null && value <= tv) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'ge') {
        if (value !== null && value >= tv) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'between') {
        if (value !== null && min <= value && value <= max) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'default') {
        color = t[type]
        flag = true
      } else if (t.term === 'null') {
        if (value === null || value === undefined || value === '') {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'not_null') {
        if (value !== null && value !== undefined && value !== '') {
          color = t[type]
          flag = true
        }
      }
      if (flag) {
        break
      } else if (i === field.conditions.length - 1) {
        color = defaultColor
      }
    } else if (field.field.deType === 0 || field.field.deType === 5) {
      if (t.term === 'eq') {
        if (value === tv) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'not_eq') {
        if (value !== tv) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'like') {
        if (value.includes(tv)) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'not like') {
        if (!value.includes(tv)) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'null') {
        if (value === null || value === undefined || value === '') {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'not_null') {
        if (value !== null && value !== undefined && value !== '') {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'default') {
        color = t[type]
        flag = true
      }
      if (flag) {
        break
      } else if (i === field.conditions.length - 1) {
        color = defaultColor
      }
    } else {
      const fc = field.conditions[i]
      if (fc.term === 'null') {
        if (value === null && value === undefined && value === '') {
          color = fc[type]
          flag = true
        }
      } else if (fc.term === 'not_null') {
        if (value !== null && value !== undefined && value !== '') {
          color = fc[type]
          flag = true
        }
      }
      if (flag) {
        break
      }
      // time
      if (!tv || !value) {
        break
      }
      tv = new Date(tv.replace(/-/g, '/') + ' GMT+8').getTime()
      const v = new Date(value.replace(/-/g, '/') + ' GMT+8').getTime()
      if (fc.term === 'eq') {
        if (v === tv) {
          color = fc[type]
          flag = true
        }
      } else if (fc.term === 'not_eq') {
        if (v !== tv) {
          color = fc[type]
          flag = true
        }
      } else if (fc.term === 'lt') {
        if (v < tv) {
          color = fc[type]
          flag = true
        }
      } else if (fc.term === 'gt') {
        if (v > tv) {
          color = fc[type]
          flag = true
        }
      } else if (fc.term === 'le') {
        if (v <= tv) {
          color = fc[type]
          flag = true
        }
      } else if (fc.term === 'ge') {
        if (v >= tv) {
          color = fc[type]
          flag = true
        }
      } else if (fc.term === 'default') {
        color = fc[type]
        flag = true
      }
      if (flag) {
        break
      } else if (i === field.conditions.length - 1) {
        color = defaultColor
      }
    }
  }
  return color
}
 
export function mappingColor(value, defaultColor, rules, type, filedValueMap?, rowData?) {
  let color = null
 
  for (let i = 0; i < rules.length; i++) {
    const { rule, sourceField } = rules[i]
    let flag = false
    const t = rule
    let targetValue, max, min
 
    let checkValue = value;
    if (sourceField.dataeaseName) {
      checkValue = rowData?.[sourceField.dataeaseName]
      if (checkValue === undefined) {
        checkValue = rowData?.query?.[sourceField.dataeaseName]
      }
    }
 
    if (t.type === 'dynamic') {
      if (t.term === 'between') {
        max = parseFloat(getValue(t.dynamicMaxField, filedValueMap, rowData))
        min = parseFloat(getValue(t.dynamicMinField, filedValueMap, rowData))
      } else {
        targetValue = getValue(t.dynamicField, filedValueMap, rowData)
      }
    } else {
      if (t.term === 'between') {
        min = parseFloat(t.min)
        max = parseFloat(t.max)
      } else {
        targetValue = t.value
      }
    }
 
    const val = checkValue;
 
    if (sourceField.deType === 2 || sourceField.deType === 3 || sourceField.deType === 4) {
      targetValue = parseFloat(targetValue)
      const numVal = parseFloat(val)
      if (t.term === 'eq') {
        if (numVal === targetValue) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'not_eq') {
        if (numVal !== targetValue) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'lt') {
        if (numVal < targetValue) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'gt') {
        if (numVal > targetValue) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'le') {
        if (val !== null && numVal <= targetValue) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'ge') {
        if (val !== null && numVal >= targetValue) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'between') {
        if (val !== null && min <= numVal && numVal <= max) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'default') {
        color = t[type]
        flag = true
      } else if (t.term === 'null') {
        if (val === null || val === undefined || val === '') {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'not_null') {
        if (val !== null && val !== undefined && val !== '') {
          color = t[type]
          flag = true
        }
      }
      if (flag) {
        break
      }
    } else if (sourceField.deType === 0 || sourceField.deType === 5) {
      if (t.term === 'eq') {
        if (val === targetValue) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'not_eq') {
        if (val !== targetValue) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'like') {
        if (val && val.includes(targetValue)) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'not like') {
        if (val && !val.includes(targetValue)) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'null') {
        if (val === null || val === undefined || val === '') {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'not_null') {
        if (val !== null && val !== undefined && val !== '') {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'default') {
        color = t[type]
        flag = true
      }
      if (flag) {
        break
      }
    } else {
      const fc = rule
      if (fc.term === 'null') {
        if (val === null || val === undefined || val === '') {
          color = fc[type]
          flag = true
        }
      } else if (fc.term === 'not_null') {
        if (val !== null && val !== undefined && val !== '') {
          color = fc[type]
          flag = true
        }
      }
      if (flag) {
        break
      }
      // time
      if (!targetValue || !val) {
        break
      } else {
          // 特殊时间格式不转换, 包含时或者包含时、分时(不包含秒), 直接比较字符串,因为new Date转换会有误差
          const isSpecialTimeFormat = (dateStyle?: string) =>
            dateStyle === 'H_m_s' || (dateStyle && dateStyle.length > 5 && dateStyle.length < 11)
 
          let v: number | string
          let compareTv = targetValue;
          if (isSpecialTimeFormat(sourceField?.dateStyle)) {
            v = val
          } else {
            v = new Date(val.replace(/-/g, '/') + ' GMT+8').getTime()
            compareTv = new Date(targetValue.toString().replace(/-/g, '/') + ' GMT+8').getTime()
          }
          if (fc.term === 'eq') {
            if (v === compareTv) {
              color = fc[type]
              flag = true
            }
          } else if (fc.term === 'not_eq') {
            if (v !== compareTv) {
              color = fc[type]
              flag = true
            }
          } else if (fc.term === 'lt') {
            if (v < compareTv) {
              color = fc[type]
              flag = true
            }
          } else if (fc.term === 'gt') {
            if (v > compareTv) {
              color = fc[type]
              flag = true
            }
          } else if (fc.term === 'le') {
            if (v <= compareTv) {
              color = fc[type]
              flag = true
            }
          } else if (fc.term === 'ge') {
            if (v >= compareTv) {
              color = fc[type]
              flag = true
            }
          } else if (fc.term === 'default') {
            color = fc[type]
            flag = true
          }
      }
      if (flag) {
        break
      }
    }
  }
 
  if (!color) {
      color = defaultColor;
  }
  return color
}
 
export function getPivotConditions(chart: Chart) {
  const { threshold } = parseJson(chart.senior)
  if (!threshold.enable) {
    return
  }
  const res = {
    text: [],
    background: []
  }
  const conditions = threshold.tableThreshold ?? []
 
  const dimFields = [...chart.xAxis, ...chart.xAxisExt].map(i => i.dataeaseName)
  const allFields = [...chart.xAxis, ...chart.xAxisExt, ...chart.yAxis]
  const fieldIdToName = allFields.reduce((acc, f) => {
    acc[f.id] = f.dataeaseName
    return acc
  }, {})
 
  if (conditions?.length > 0) {
    const { tableCell, basicStyle, tableHeader } = parseJson(chart.customAttr)
    const enableTableCrossBG = tableCell.enableTableCrossBG
    // 单元格字体颜色
    const valueColor = isAlphaColor(tableCell.tableFontColor)
      ? tableCell.tableFontColor
      : hexColorToRGBA(tableCell.tableFontColor, basicStyle.alpha)
    // 单元格背景颜色
    const valueBgColor = enableTableCrossBG
      ? null
      : isAlphaColor(tableCell.tableItemBgColor)
      ? tableCell.tableItemBgColor
      : hexColorToRGBA(tableCell.tableItemBgColor, basicStyle.alpha)
    // 列头字体颜色
    const colHeaderValueColor = isAlphaColor(tableHeader.tableHeaderFontColor)
      ? tableHeader.tableHeaderFontColor
      : hexColorToRGBA(tableHeader.tableHeaderFontColor, basicStyle.alpha)
    // 列头背景颜色
    const colHeaderBgColor = isAlphaColor(tableHeader.tableHeaderBgColor)
      ? tableHeader.tableHeaderBgColor
      : hexColorToRGBA(tableHeader.tableHeaderBgColor, basicStyle.alpha)
    // 行头字体颜色
    const rowHeaderValueColor = isAlphaColor(tableHeader.tableHeaderColFontColor)
    ? tableHeader.tableHeaderColFontColor
    : hexColorToRGBA(tableHeader.tableHeaderColFontColor, basicStyle.alpha)
    // 行头背景颜色
    const rowHeaderBgColor = isAlphaColor(tableHeader.tableHeaderColBgColor)
      ? tableHeader.tableHeaderColBgColor
      : hexColorToRGBA(tableHeader.tableHeaderColBgColor, basicStyle.alpha)
    const filedValueMap = getFieldValueMap(chart)
 
    
 
    const targetRulesMap = {} // columnName -> Array<{ rule, sourceField }>
    const xFields = chart.xAxis.map(f => f.dataeaseName)
    const xExtFields = chart.xAxisExt.map(f => f.dataeaseName)
    const yFields = chart.yAxis.map(f => f.dataeaseName)
    for (let i = 0; i < conditions.length; i++) {
      const fieldItem = conditions[i]
      if (!fieldItem.conditions) continue;
 
      for (let j = 0; j < fieldItem.conditions.length; j++) {
        const rule = fieldItem.conditions[j]
        let targets = []
        if (rule.target === 'total_row') {
          if (xFields.includes(fieldItem.field.dataeaseName)) {
            targets.push(...xFields)
            if (basicStyle.quotaPosition === 'row') {
              targets.push(EXTRA_FIELD)
            }
          }
          if (xExtFields.includes(fieldItem.field.dataeaseName)) {
            targets.push(...xExtFields)
            if (basicStyle.quotaPosition !== 'row') {
              targets.push(EXTRA_FIELD)
            }
          }
          targets.push(...yFields)
        } else if (rule.target === 'custom' && rule.targetFieldId) {
          const targetName = fieldIdToName[rule.targetFieldId]
          if (targetName) targets = [targetName]
        } else {
          targets = [fieldItem.field.dataeaseName]
        }
 
        targets.forEach(targetName => {
          if (!targetRulesMap[targetName]) {
            targetRulesMap[targetName] = []
          }
          targetRulesMap[targetName].push({
            rule: rule,
            sourceField: fieldItem.field
          })
        })
      }
    }
 
    for (const targetName in targetRulesMap) {
      const rules = targetRulesMap[targetName]
      let defaultValueColor = valueColor
      let defaultBgColor = valueBgColor
      if (xFields.includes(targetName)) {
        defaultValueColor = rowHeaderValueColor
        defaultBgColor = rowHeaderBgColor
      }
      if (xExtFields.includes(targetName)) {
        defaultValueColor = colHeaderValueColor
        defaultBgColor = colHeaderBgColor
      }
 
      res.text.push({
        field: targetName,
        mapping(value, rowData) {
          if (!value && !rowData) {
            return null
          }
          // 角头
          if (rowData.cornerType) {
            return null
          }
 
          return {
            fill: mappingPivotColor(value, defaultValueColor, rules.toReversed(), 'color', filedValueMap, rowData)
          }
        }
      })
      res.background.push({
        field: targetName,
        mapping(value, rowData) {
          if (!value && !rowData) {
            return null
          }
          // 角头
          if (rowData.cornerType) {
            return null
          }
          
          const fill = mappingPivotColor(
            value,
            defaultBgColor,
            rules.toReversed(),
            'backgroundColor',
            filedValueMap,
            rowData
          )
          if (isTransparent(fill)) {
            return null
          }
          return { fill }
        }
      })
    }
  }
  return res
}
 
export function mappingPivotColor(value, defaultColor, rules, type, filedValueMap?, rowData?) {
  let color = null
 
  for (let i = 0; i < rules.length; i++) {
    const { rule, sourceField } = rules[i]
    let flag = false
    const t = rule
    let targetValue, max, min
 
    let checkValue = value;
    if (sourceField.dataeaseName) {
      checkValue = rowData?.[sourceField.dataeaseName]
      if (checkValue === undefined) {
        checkValue = rowData?.query?.[sourceField.dataeaseName]
      }
    }
 
    if (rowData.isGrandTotals || rowData.isSubTotals) {
      if (rule.target !== 'total_row') {
        return null
      }
      checkValue = rowData?.query?.[sourceField.dataeaseName]
    }
 
    if (rowData.field === EXTRA_FIELD) {
      if (rule.target !== 'total_row') {
        return null
      }
      checkValue = rowData?.query?.[sourceField.dataeaseName]
    }
    if (checkValue === undefined) {
      return null
    }
 
    if (t.type === 'dynamic') {
      if (t.term === 'between') {
        max = parseFloat(getValue(t.dynamicMaxField, filedValueMap, rowData))
        min = parseFloat(getValue(t.dynamicMinField, filedValueMap, rowData))
      } else {
        targetValue = getValue(t.dynamicField, filedValueMap, rowData)
      }
    } else {
      if (t.term === 'between') {
        min = parseFloat(t.min)
        max = parseFloat(t.max)
      } else {
        targetValue = t.value
      }
    }
 
    const val = checkValue;
 
    if (sourceField.deType === 2 || sourceField.deType === 3 || sourceField.deType === 4) {
      targetValue = parseFloat(targetValue)
      const numVal = parseFloat(val)
      if (t.term === 'eq') {
        if (numVal === targetValue) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'not_eq') {
        if (numVal !== targetValue) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'lt') {
        if (numVal < targetValue) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'gt') {
        if (numVal > targetValue) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'le') {
        if (val !== null && numVal <= targetValue) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'ge') {
        if (val !== null && numVal >= targetValue) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'between') {
        if (val !== null && min <= numVal && numVal <= max) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'default') {
        color = t[type]
        flag = true
      } else if (t.term === 'null') {
        if (val === null || val === undefined || val === '') {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'not_null') {
        if (val !== null && val !== undefined && val !== '') {
          color = t[type]
          flag = true
        }
      }
      if (flag) {
        break
      }
    } else if (sourceField.deType === 0 || sourceField.deType === 5) {
      if (t.term === 'eq') {
        if (val === targetValue) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'not_eq') {
        if (val !== targetValue) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'like') {
        if (val && val.includes(targetValue)) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'not like') {
        if (val && !val.includes(targetValue)) {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'null') {
        if (val === null || val === undefined || val === '') {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'not_null') {
        if (val !== null && val !== undefined && val !== '') {
          color = t[type]
          flag = true
        }
      } else if (t.term === 'default') {
        color = t[type]
        flag = true
      }
      if (flag) {
        break
      }
    } else {
      const fc = rule
      if (fc.term === 'null') {
        if (val === null || val === undefined || val === '') {
          color = fc[type]
          flag = true
        }
      } else if (fc.term === 'not_null') {
        if (val !== null && val !== undefined && val !== '') {
          color = fc[type]
          flag = true
        }
      }
      if (flag) {
        break
      }
      // time
      if (!targetValue || !val) {
        break
      } else {
          // 特殊时间格式不转换, 包含时或者包含时、分时(不包含秒), 直接比较字符串,因为new Date转换会有误差
          const isSpecialTimeFormat = (dateStyle?: string) =>
            dateStyle === 'H_m_s' || (dateStyle && dateStyle.length > 5 && dateStyle.length < 11)
 
          let v: number | string
          let compareTv = targetValue;
          if (isSpecialTimeFormat(sourceField?.dateStyle)) {
            v = val
          } else {
            v = new Date(val.replace(/-/g, '/') + ' GMT+8').getTime()
            compareTv = new Date(targetValue.toString().replace(/-/g, '/') + ' GMT+8').getTime()
          }
          if (fc.term === 'eq') {
            if (v === compareTv) {
              color = fc[type]
              flag = true
            }
          } else if (fc.term === 'not_eq') {
            if (v !== compareTv) {
              color = fc[type]
              flag = true
            }
          } else if (fc.term === 'lt') {
            if (v < compareTv) {
              color = fc[type]
              flag = true
            }
          } else if (fc.term === 'gt') {
            if (v > compareTv) {
              color = fc[type]
              flag = true
            }
          } else if (fc.term === 'le') {
            if (v <= compareTv) {
              color = fc[type]
              flag = true
            }
          } else if (fc.term === 'ge') {
            if (v >= compareTv) {
              color = fc[type]
              flag = true
            }
          } else if (fc.term === 'default') {
            color = fc[type]
            flag = true
          }
      }
      if (flag) {
        break
      }
    }
  }
 
  if (!color) {
      color = defaultColor;
  }
  return color
}
 
function getFieldValueMap(view) {
  const fieldValueMap = {}
  if (view.data && view.data.dynamicAssistLines && view.data.dynamicAssistLines.length > 0) {
    view.data.dynamicAssistLines.forEach(ele => {
      fieldValueMap[ele.summary + '-' + ele.fieldId] = ele.value
    })
  }
  return fieldValueMap
}
 
function getValue(field, filedValueMap, rowData) {
  if (field.summary === 'value') {
    // 单元格数据
    let value =  rowData?.[field.field?.dataeaseName]
    // 表头数据
    if (value === undefined) {
      value = rowData.query?.[field.field?.dataeaseName]
    }
    return value
  } else {
    return filedValueMap[field.summary + '-' + field.fieldId]
  }
}
 
export function handleTableEmptyStrategy(chart: Chart) {
  let newData = (chart.data?.tableRow || []) as Record<string, any>[]
  let intersectionArr = []
  const senior = parseJson(chart.senior)
  let emptyDataStrategy = senior?.functionCfg?.emptyDataStrategy
  if (!emptyDataStrategy) {
    emptyDataStrategy = 'breakLine'
  }
  const emptyDataFieldCtrl = senior?.functionCfg?.emptyDataFieldCtrl
  if (emptyDataStrategy !== 'breakLine' && emptyDataFieldCtrl?.length && newData?.length) {
    const deNames = keys(newData[0])
    intersectionArr = intersection(deNames, emptyDataFieldCtrl)
  }
  if (intersectionArr.length) {
    newData = cloneDeep(newData)
    for (let i = newData.length - 1; i >= 0; i--) {
      for (let j = 0, tmp = intersectionArr.length; j < tmp; j++) {
        const deName = intersectionArr[j]
        if (newData[i][deName] === null) {
          if (emptyDataStrategy === 'setZero') {
            newData[i][deName] = 0
          }
          if (emptyDataStrategy === 'ignoreData') {
            newData = filter(newData, (_, index) => index !== i)
            break
          }
        }
      }
    }
  }
  return newData
}
 
export class SortTooltip extends BaseTooltip {
  show(showOptions) {
    const { iconName } = showOptions
    if (iconName) {
      this.showSortTooltip(showOptions)
      return
    }
    super.show(showOptions)
  }
 
  showSortTooltip(showOptions) {
    const { position, options, meta, event } = showOptions
    const { enterable } = getTooltipDefaultOptions(options)
    const { autoAdjustBoundary, adjustPosition } = this.spreadsheet.options.tooltip || {}
    this.visible = true
    this.options = showOptions
    const container = this['getContainer']()
    // 用 vue 手动 patch
    const vNode = createVNode(TableTooltip, {
      table: this.spreadsheet,
      meta
    })
    this.spreadsheet.tooltip.container.innerHTML = ''
    const childElement = document.createElement('div')
    this.spreadsheet.tooltip.container.appendChild(childElement)
    render(vNode, childElement)
 
    const { x, y } = getAutoAdjustPosition({
      spreadsheet: this.spreadsheet,
      position,
      tooltipContainer: container,
      autoAdjustBoundary
    })
 
    this.position = adjustPosition?.({ position: { x, y }, event }) ?? {
      x,
      y
    }
 
    setTooltipContainerStyle(container, {
      style: {
        left: `${this.position?.x}px`,
        top: `${this.position?.y}px`,
        pointerEvents: enterable ? 'all' : 'none',
        zIndex: 9999,
        position: 'absolute',
        color: 'black',
        background: 'white',
        fontSize: '16px'
      },
      visible: true
    })
  }
}
 
const SORT_DEFAULT =
  '<svg t="1711681787276" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4355" width="200" height="200"><path d="M922.345786 372.183628l-39.393195 38.687114L676.138314 211.079416l0 683.909301-54.713113 0L621.425202 129.010259l53.320393 0L922.345786 372.183628zM349.254406 894.989741 101.654214 651.815349l39.393195-38.687114 206.814276 199.792349L347.861686 129.010259l54.713113 0 0 765.978459L349.254406 894.988718z" fill="{fill}" p-id="4356"></path></svg>'
const SORT_UP =
  '<svg t="1711682928245" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="11756" width="200" height="200"><path d="M960 704L512 256 64 704z" fill="{fill}" p-id="11757"></path></svg>'
const SORT_DOWN =
  '<svg t="1711681879346" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4655" width="200" height="200"><path d="M64 320l448 448 448-448z" fill="{fill}" p-id="4656"></path></svg>'
 
function svg2Base64(svg) {
  return `data:image/svg+xml;charset=utf-8;base64,${btoa(svg)}`
}
 
export function configHeaderInteraction(chart: Chart, option: S2Options) {
  const { tableHeaderFontColor, tableHeaderSort } = parseJson(chart.customAttr).tableHeader
  if (!tableHeaderSort) {
    return
  }
  const iconColor = tableHeaderFontColor ?? '#666'
  const sortDefault = svg2Base64(SORT_DEFAULT.replace('{fill}', iconColor))
  const sortUp = svg2Base64(SORT_UP.replace('{fill}', iconColor))
  const sortDown = svg2Base64(SORT_DOWN.replace('{fill}', iconColor))
  // 防止缓存
  const randomSuffix = Math.random()
  const sortIconMap = {
    asc: `customSortUp${randomSuffix}`,
    desc: `customSortDown${randomSuffix}`
  }
  option.customSVGIcons = [
    {
      name: `customSortDefault${randomSuffix}`,
      svg: sortDefault
    },
    {
      name: `customSortUp${randomSuffix}`,
      svg: sortUp
    },
    {
      name: `customSortDown${randomSuffix}`,
      svg: sortDown
    }
  ]
  option.headerActionIcons = [
    {
      iconNames: [
        `customSortDefault${randomSuffix}`,
        `customSortUp${randomSuffix}`,
        `customSortDown${randomSuffix}`
      ],
      belongsCell: 'colCell',
      displayCondition: (meta, iconName) => {
        if (meta.field === SERIES_NUMBER_FIELD) {
          return false
        }
        // 分组
        if (meta.colIndex === -1) {
          return false
        }
        const sortMethodMap = meta.spreadsheet.store.get('sortMethodMap')
        const sortType = sortMethodMap?.[meta.field]
        if (sortType) {
          return iconName === sortIconMap[sortType]
        }
        return iconName === `customSortDefault${randomSuffix}`
      },
      onClick: props => {
        const { meta, event } = props
        meta.spreadsheet.showTooltip({
          position: {
            x: event.clientX,
            y: event.clientY
          },
          event,
          ...props
        })
        const parent = document.getElementById(chart.container)
        if (parent?.childNodes?.length) {
          const child = Array.from(parent.childNodes)
            .filter(node => node.nodeType === Node.ELEMENT_NODE)
            .find(node => node.classList.contains('antv-s2-tooltip-container'))
          if (child) {
            const left = child.offsetLeft + child.clientWidth
            if (left > parent.offsetWidth) {
              const newLeft = parent.offsetWidth - child.clientWidth - 10
              child.style.left = `${newLeft}px`
            }
          }
        }
      }
    }
  ]
}
 
export function configTooltip(chart: Chart, option: S2Options) {
  const { tooltip } = parseJson(chart.customAttr)
  const textFontFamily = chart.fontFamily ? chart.fontFamily : FONT_FAMILY
  option.tooltip = {
    ...option.tooltip,
    style: {
      background: tooltip.backgroundColor,
      fontSize: tooltip.fontSize + 'px',
      fontFamily: textFontFamily,
      color: tooltip.color,
      boxShadow: 'rgba(0, 0, 0, 0.1) 0px 4px 8px 0px',
      borderRadius: '3px',
      padding: '4px 12px',
      opacity: 0.95,
      position: 'absolute'
    },
    adjustPosition: ({ event }) => {
      return getTooltipPosition(event)
    }
  }
}
 
export function copyContent(s2Instance: SpreadSheet, event, fieldMeta) {
  event.preventDefault()
  const cell = s2Instance.getCell(event.target)
  const valueField = cell.getMeta().valueField
  const cellMeta = cell.getMeta()
  const selectState = s2Instance.interaction.getState()
  let content = ''
  // 多选
  if (selectState.stateName === InteractionStateName.SELECTED) {
    const { cells } = selectState
    if (!cells?.length) {
      return
    }
    if (cells.length === 1) {
      const curCell = cells[0]
      if (cell.getMeta().id === curCell.id) {
        const cellMeta = cell.getMeta()
        const valueField = cellMeta.valueField
        const value = cellMeta.data?.[valueField]
        const metaObj = find(fieldMeta, m => m.field === valueField)
        let fieldVal = value?.toString()
        if (metaObj) {
          fieldVal = metaObj.formatter(value)
        }
        if (fieldVal === undefined || fieldVal === null) {
          const fieldMap = fieldMeta?.reduce((p, n) => {
            p[n.field] = n.name
            return p
          }, {})
          fieldVal = cellMeta.value
          if (fieldMap?.[fieldVal]) {
            fieldVal = fieldMap[fieldVal]
          }
        }
        copyString(fieldVal, true)
      }
      s2Instance.interaction.clearState()
      return
    }
    const brushSelection = s2Instance.interaction.interactions.get(
      InteractionName.BRUSH_SELECTION
    ) as DataCellBrushSelection
    const selectedCells: TableDataCell[] = brushSelection.getScrollBrushRangeCells(cells)
    selectedCells.sort((a, b) => {
      const aMeta = a.getMeta()
      const bMeta = b.getMeta()
      if (aMeta.rowIndex !== bMeta.rowIndex) {
        return aMeta.rowIndex - bMeta.rowIndex
      }
      return aMeta.colIndex - bMeta.colIndex
    })
    // 点击已选的就复制,未选的就忽略
    let validClick = false
    const matrix = selectedCells.reduce((p, n) => {
      if (
        n.getMeta().colIndex === cellMeta.colIndex &&
        n.getMeta().rowIndex === cellMeta.rowIndex
      ) {
        validClick = true
      }
      const arr = p[n.getMeta().rowIndex]
      if (!arr) {
        p[n.getMeta().rowIndex] = [n]
      } else {
        arr.push(n)
      }
      return p
    }, {}) as Record<number, TableDataCell[]>
    if (validClick) {
      keys(matrix).forEach(k => {
        const arr = matrix[k] as TableDataCell[]
        arr.forEach((cell, index) => {
          const cellMeta = cell.getMeta()
          const valueField = cellMeta.valueField
          const value = cellMeta.data?.[valueField]
          const metaObj = find(fieldMeta, m => m.field === valueField)
          let fieldVal = value?.toString()
          if (metaObj) {
            fieldVal = metaObj.formatter(value)
          }
          if (fieldVal === undefined || fieldVal === null) {
            const fieldMap = fieldMeta?.reduce((p, n) => {
              p[n.field] = n.name
              return p
            }, {})
            fieldVal = cellMeta.value
            if (fieldMap?.[fieldVal]) {
              fieldVal = fieldMap[fieldVal]
            }
          }
          if (fieldVal === undefined || fieldVal === null) {
            fieldVal = ''
          }
          if (index !== arr.length - 1) {
            fieldVal += '\t'
          }
          content += fieldVal
        })
        content = content + '\n'
      })
      if (content) {
        copyString(content, true)
      }
    }
    s2Instance.interaction.clearState()
    return
  }
  // 单元格
  if (cellMeta?.data) {
    const value = cellMeta.data[valueField]
    const metaObj = find(fieldMeta, m => m.field === valueField)
    content = value?.toString()
    if (metaObj) {
      content = metaObj.formatter(value)
    }
  } else {
    // 列头&行头
    const fieldMap = fieldMeta?.reduce((p, n) => {
      p[n.field] = n.name
      return p
    }, {})
    content = cellMeta.value
    if (fieldMap?.[content]) {
      content = fieldMap[content]
    }
  }
  if (content) {
    copyString(content, true)
  }
}
 
function getTooltipPosition(event) {
  const s2Instance = event.s2Instance
  const { x, y } = event
  const result = { x: x + 15, y }
  if (!s2Instance) {
    return result
  }
  const { height, width } = s2Instance.getCanvasElement().getBoundingClientRect()
  const { offsetHeight, offsetWidth } = s2Instance.tooltip.getContainer()
  if (offsetWidth > width) {
    result.x = 0
  }
  if (offsetHeight > height) {
    result.y = 0
  }
  if (!(result.x || result.y)) {
    return result
  }
  if (result.x && result.x + offsetWidth > width) {
    result.x -= result.x + offsetWidth - width
  }
  if (result.y) {
    if (result.y > offsetHeight) {
      if (result.y - offsetHeight >= 15) {
        result.y -= offsetHeight + 15
      } else {
        result.y = 0
      }
    } else {
      result.y += 15
    }
  }
  return result
}
 
export async function exportGridPivot(instance: PivotSheet, chart: ChartObj) {
  const { layoutResult } = instance.facet
  const { meta, fields } = instance.dataCfg
  const rowLength = fields?.rows?.length || 0
  const colLength = fields?.columns?.length || 0
  const colNums = layoutResult.colLeafNodes.length + rowLength
  if (colNums > 16384) {
    ElMessage.warning(i18nt('chart.pivot_export_invalid_col_exceed'))
    return
  }
  const workbook = new Exceljs.Workbook()
  const worksheet = workbook.addWorksheet(i18nt('chart.chart_data'))
  const metaMap: Record<string, Meta> = meta?.reduce((p, n) => {
    if (n.field) {
      p[n.field] = n
    }
    return p
  }, {})
  // 角头
  fields.columns?.forEach((column, index) => {
    const cell = worksheet.getCell(index + 1, 1)
    cell.value = metaMap[column]?.name ?? column
    cell.alignment = { vertical: 'middle', horizontal: 'center' }
    if (rowLength >= 2) {
      worksheet.mergeCells(index + 1, 1, index + 1, rowLength)
    }
    cell.border = {
      right: { style: 'thick', color: { argb: '00000000' } }
    }
  })
  fields?.rows?.forEach((row, index) => {
    const cell = worksheet.getCell(colLength + 1, index + 1)
    cell.value = metaMap[row]?.name ?? row
    cell.alignment = { vertical: 'middle', horizontal: 'center' }
    cell.border = {
      bottom: { style: 'thick', color: { argb: '00000000' } }
    }
    if (index === fields.rows.length - 1) {
      cell.border.right = { style: 'thick', color: { argb: '00000000' } }
    }
  })
  // 行头
  const { rowLeafNodes, rowsHierarchy, rowNodes } = layoutResult
  const maxColIndex = rowsHierarchy.maxLevel + 1
  const notLeafNodeHeightMap: Record<string, number> = {}
  rowLeafNodes.forEach(node => {
    // 行头的高度由子节点相加决定,也就是行头子节点中包含的叶子节点数量
    let curNode = node.parent
    while (curNode) {
      const height = notLeafNodeHeightMap[curNode.id] ?? 0
      notLeafNodeHeightMap[curNode.id] = height + 1
      curNode = curNode.parent
    }
    const { rowIndex } = node
    const writeRowIndex = rowIndex + 1 + colLength + 1
    const writeColIndex = node.level + 1
    const cell = worksheet.getCell(writeRowIndex, writeColIndex)
    cell.value = node.label
    cell.alignment = { vertical: 'middle', horizontal: 'center' }
    if (writeColIndex < maxColIndex) {
      worksheet.mergeCells(writeRowIndex, writeColIndex, writeRowIndex, maxColIndex)
    }
    cell.border = {
      right: { style: 'thick', color: { argb: '00000000' } }
    }
  })
 
  const getNodeStartRowIndex = (node: Node) => {
    if (!node.children?.length) {
      return node.rowIndex + 1
    } else {
      return getNodeStartRowIndex(node.children[0])
    }
  }
  rowNodes?.forEach(node => {
    if (node.isLeaf) {
      return
    }
    const rowIndex = getNodeStartRowIndex(node)
    const height = notLeafNodeHeightMap[node.id]
    const writeRowIndex = rowIndex + colLength + 1
    const mergeColCount = node.children[0].level - node.level
    const value = node.label
    const cell = worksheet.getCell(writeRowIndex, node.level + 1)
    cell.value = value
    cell.alignment = { vertical: 'middle', horizontal: 'center' }
    if (mergeColCount > 1 || height > 1) {
      worksheet.mergeCells(
        writeRowIndex,
        node.level + 1,
        writeRowIndex + height - 1,
        node.level + mergeColCount
      )
    }
  })
 
  // 列头
  const { colLeafNodes, colNodes, colsHierarchy } = layoutResult
  const maxColHeight = colsHierarchy.maxLevel + 1
  const notLeafNodeWidthMap: Record<string, number> = {}
  colLeafNodes.forEach(node => {
    // 列头的宽度由子节点相加决定,也就是列头子节点中包含的叶子节点数量
    let curNode = node.parent
    while (curNode) {
      const width = notLeafNodeWidthMap[curNode.id] ?? 0
      notLeafNodeWidthMap[curNode.id] = width + 1
      curNode = curNode.parent
    }
    const { colIndex } = node
    const writeRowIndex = node.level + 1
    const writeColIndex = colIndex + 1 + rowLength
    const cell = worksheet.getCell(writeRowIndex, writeColIndex)
    let value = node.label
    if (node.field === '$$extra$$' && metaMap[value]?.name) {
      value = metaMap[value].name
    }
    cell.value = value
    cell.alignment = { vertical: 'middle', horizontal: 'center' }
    if (writeRowIndex < maxColHeight) {
      worksheet.mergeCells(writeRowIndex, writeColIndex, maxColHeight, writeColIndex)
    }
    cell.border = {
      bottom: { style: 'thick', color: { argb: '00000000' } }
    }
  })
  const getNodeStartColIndex = (node: Node) => {
    if (!node.children?.length) {
      return node.colIndex + 1
    } else {
      return getNodeStartColIndex(node.children[0])
    }
  }
  colNodes.forEach(node => {
    if (node.isLeaf) {
      return
    }
    const colIndex = getNodeStartColIndex(node)
    const width = notLeafNodeWidthMap[node.id]
    const writeRowIndex = node.level + 1
    const mergeRowCount = node.children[0].level - node.level
    const value = node.label
    const writeColIndex = colIndex + rowLength
    const cell = worksheet.getCell(writeRowIndex, writeColIndex)
    cell.value = value
    cell.alignment = { vertical: 'middle', horizontal: 'center' }
    if (mergeRowCount > 1 || width > 1) {
      worksheet.mergeCells(
        writeRowIndex,
        writeColIndex,
        writeRowIndex + mergeRowCount - 1,
        writeColIndex + width - 1
      )
    }
  })
  const formatterMap = chart.yAxis.reduce((p, n) => {
    if (n.dataeaseName) {
      p[n.dataeaseName] = n.formatterCfg
    }
    return p
  }, {})
  //  单元格数据
  for (let rowIndex = 0; rowIndex < rowLeafNodes.length; rowIndex++) {
    for (let colIndex = 0; colIndex < colLeafNodes.length; colIndex++) {
      const dataCellMeta = layoutResult.getCellMeta(rowIndex, colIndex)
      const { fieldValue } = dataCellMeta
      const cell = worksheet.getCell(rowIndex + maxColHeight + 1, rowLength + colIndex + 1)
      cell.alignment = { vertical: 'middle', horizontal: 'center' }
      if (fieldValue === "-" || fieldValue === null || fieldValue === undefined) {
        cell.value = '-'
        continue
      }
      const meta = metaMap[dataCellMeta.valueField]
      const value = meta?.formatter?.(fieldValue) || fieldValue
      if (typeof value === 'number') {
        cell.value = value
      } else if (typeof value === 'string') {
        const formatterCfg = formatterMap?.[dataCellMeta.valueField]
        const result = extractNumber(value, formatterCfg)
        if (typeof result === 'string') {
          cell.value = result
        } else {
          cell.value = result.value
          cell.numFmt = result.numFmt
        }
      }
    }
  }
  const buffer = await workbook.xlsx.writeBuffer()
  const dataBlob = new Blob([buffer], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
  })
  saveAs(dataBlob, `${chart.title ?? '透视表'}.xlsx`)
}
 
export async function exportRowQuotaGridPivot(instance: PivotSheet, chart: ChartObj) {
  const { layoutResult } = instance.facet
  const { meta, fields } = instance.dataCfg
  const rowLength = fields?.rows?.length || 0
  const colLength = fields?.columns?.length || 0
  const colNums = layoutResult.colLeafNodes.length + rowLength
  if (colNums > 16384) {
    ElMessage.warning(i18nt('chart.pivot_export_invalid_col_exceed'))
    return
  }
  const workbook = new Exceljs.Workbook()
  const worksheet = workbook.addWorksheet(i18nt('chart.chart_data'))
  const metaMap: Record<string, Meta> = meta?.reduce((p, n) => {
    if (n.field) {
      p[n.field] = n
    }
    return p
  }, {})
  // 角头
  if (colLength > 1) {
    fields.columns.forEach((column: string, index) => {
      if (index >= colLength - 1) {
        return
      }
      const cell = worksheet.getCell(index + 1, 1)
      cell.value = metaMap[column]?.name ?? column
      cell.alignment = { vertical: 'middle', horizontal: 'center' }
      cell.border = {
        right: { style: 'thick', color: { argb: '00000000' } }
      }
      worksheet.mergeCells(index + 1, 1, index + 1, rowLength + 1)
    })
  }
  fields?.rows?.forEach((row, index) => {
    const cell = worksheet.getCell(colLength === 0 ? 1 : colLength, index + 1)
    cell.value = metaMap[row]?.name ?? row
    cell.alignment = { vertical: 'middle', horizontal: 'center' }
    cell.border = { bottom: { style: 'thick', color: { argb: '00000000' } } }
  })
  const quotaColLabel = chart.customAttr.basicStyle.quotaColLabel ?? t('dataset.value')
  const quotaColHeadCell = worksheet.getCell(colLength === 0 ? 1 : colLength, rowLength + 1)
  quotaColHeadCell.value = quotaColLabel
  quotaColHeadCell.alignment = { vertical: 'middle', horizontal: 'center' }
  quotaColHeadCell.border = {
    bottom: { style: 'thick', color: { argb: '00000000' } },
    right: { style: 'thick', color: { argb: '00000000' } }
  }
  // 行头
  const { rowLeafNodes, rowNodes } = layoutResult
  const notLeafNodeHeightMap: Record<string, number> = {}
  rowLeafNodes.forEach(node => {
    // 行头的高度由子节点相加决定,也就是行头子节点中包含的叶子节点数量
    let curNode = node.parent
    while (curNode) {
      const height = notLeafNodeHeightMap[curNode.id] ?? 0
      notLeafNodeHeightMap[curNode.id] = height + 1
      curNode = curNode.parent
    }
    const { rowIndex } = node
    const writeRowIndex = rowIndex + 2 + (colLength === 0 ? 1 : colLength - 1)
    const writeColIndex = node.level + 1
    const cell = worksheet.getCell(writeRowIndex, writeColIndex)
    let value = node.label
    if (node.field === '$$extra$$' && metaMap[value]?.name) {
      value = metaMap[value].name
    }
    cell.value = value
    cell.alignment = { vertical: 'middle', horizontal: 'center' }
    cell.border = {
      right: { style: 'thick', color: { argb: '00000000' } }
    }
  })
 
  const getNodeStartRowIndex = (node: Node) => {
    if (!node.children?.length) {
      return node.rowIndex + 1
    } else {
      return getNodeStartRowIndex(node.children[0])
    }
  }
  rowNodes?.forEach(node => {
    if (node.isLeaf) {
      return
    }
    const rowIndex = getNodeStartRowIndex(node)
    const height = notLeafNodeHeightMap[node.id]
    const writeRowIndex = rowIndex + 1 + (colLength === 0 ? 1 : colLength - 1)
    const mergeColCount = node.children[0].level - node.level
    const cell = worksheet.getCell(writeRowIndex, node.level + 1)
    cell.value = node.label
    cell.alignment = { vertical: 'middle', horizontal: 'center' }
    if (mergeColCount > 1 || height > 1) {
      worksheet.mergeCells(
        writeRowIndex,
        node.level + 1,
        writeRowIndex + height - 1,
        node.level + mergeColCount
      )
    }
  })
 
  // 列头
  const { colLeafNodes, colNodes, colsHierarchy } = layoutResult
  const maxColHeight = colsHierarchy.maxLevel + 1
  const notLeafNodeWidthMap: Record<string, number> = {}
  colLeafNodes.forEach(node => {
    // 列头的宽度由子节点相加决定,也就是列头子节点中包含的叶子节点数量
    let curNode = node.parent
    while (curNode) {
      const width = notLeafNodeWidthMap[curNode.id] ?? 0
      notLeafNodeWidthMap[curNode.id] = width + 1
      curNode = curNode.parent
    }
    const { colIndex } = node
    const writeRowIndex = node.level + 1
    const writeColIndex = colIndex + rowLength + 2
    const cell = worksheet.getCell(writeRowIndex, writeColIndex)
    const value = node.label
    cell.value = value
    cell.alignment = { vertical: 'middle', horizontal: 'center' }
    if (writeRowIndex < maxColHeight) {
      worksheet.mergeCells(writeRowIndex, writeColIndex, maxColHeight, writeColIndex)
    }
    cell.border = {
      bottom: { style: 'thick', color: { argb: '00000000' } }
    }
  })
  const getNodeStartColIndex = (node: Node) => {
    if (!node.children?.length) {
      return node.colIndex + 1
    } else {
      return getNodeStartColIndex(node.children[0])
    }
  }
  colNodes.forEach(node => {
    if (node.isLeaf) {
      return
    }
    const colIndex = getNodeStartColIndex(node)
    const width = notLeafNodeWidthMap[node.id]
    const writeRowIndex = node.level + 1
    const value = node.label
    const writeColIndex = colIndex + rowLength + 1
    const cell = worksheet.getCell(writeRowIndex, writeColIndex)
    cell.value = value
    cell.alignment = { vertical: 'middle', horizontal: 'center' }
    if (width > 1) {
      worksheet.mergeCells(writeRowIndex, writeColIndex, writeRowIndex, writeColIndex + width - 1)
    }
  })
  const formatterMap = chart.yAxis.reduce((p, n) => {
    if (n.dataeaseName) {
      p[n.dataeaseName] = n.formatterCfg
    }
    return p
  }, {})
  //  单元格数据
  for (let rowIndex = 0; rowIndex < rowLeafNodes.length; rowIndex++) {
    for (let colIndex = 0; colIndex < colLeafNodes.length; colIndex++) {
      const dataCellMeta = layoutResult.getCellMeta(rowIndex, colIndex)
      const { fieldValue } = dataCellMeta
      const cell = worksheet.getCell(rowIndex + maxColHeight + 1, rowLength + colIndex + 2)
      cell.alignment = { vertical: 'middle', horizontal: 'center' }
      if (fieldValue === "-" || fieldValue === null || fieldValue === undefined) {
        cell.value = '-'
        continue
      }
      const meta = metaMap[dataCellMeta.valueField]
      const value = meta?.formatter?.(fieldValue) || fieldValue
      if (typeof value === 'number') {
        cell.value = value
      } else if (typeof value === 'string') {
        const formatterCfg = formatterMap?.[dataCellMeta.valueField]
        const result = extractNumber(value, formatterCfg)
        if (typeof result === 'string') {
          cell.value = result
        } else {
          cell.value = result.value
          cell.numFmt = result.numFmt
        }
      }
    }
  }
  const buffer = await workbook.xlsx.writeBuffer()
  const dataBlob = new Blob([buffer], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
  })
  saveAs(dataBlob, `${chart.title ?? '透视表'}.xlsx`)
}
 
export async function exportTreePivot(instance: PivotSheet, chart: ChartObj) {
  const layoutResult = instance.facet.layoutResult
  if (layoutResult.colLeafNodes.length + 1 > 16384) {
    ElMessage.warning(i18nt('chart.pivot_export_invalid_col_exceed'))
    return
  }
  const { meta, fields } = instance.dataCfg
  const colLength = fields?.columns?.length || 0
  const workbook = new Exceljs.Workbook()
  const worksheet = workbook.addWorksheet(i18nt('chart.chart_data'))
  const metaMap: Record<string, Meta> = meta?.reduce((p, n) => {
    if (n.field) {
      p[n.field] = n
    }
    return p
  }, {})
 
  // 角头
  fields.columns?.forEach((column, index) => {
    const cell = worksheet.getCell(index + 1, 1)
    cell.value = metaMap[column]?.name ?? column
    cell.alignment = { vertical: 'middle', horizontal: 'center' }
    cell.border = {
      right: { style: 'thick', color: { argb: '00000000' } }
    }
  })
  const maxColHeight = layoutResult.colsHierarchy.maxLevel + 1
  const rowName = fields?.rows?.map(row => metaMap[row]?.name ?? row).join('/')
  const cell = worksheet.getCell(colLength + 1, 1)
  cell.value = rowName
  cell.alignment = { vertical: 'middle', horizontal: 'center' }
  cell.border = {
    right: { style: 'thick', color: { argb: '00000000' } },
    bottom: { style: 'thick', color: { argb: '00000000' } }
  }
  //行头
  const { rowLeafNodes } = layoutResult
  rowLeafNodes.forEach((node, index) => {
    const cell = worksheet.getCell(maxColHeight + index + 1, 1)
    cell.value = repeat('  ', node.level) + node.label
    cell.alignment = { vertical: 'middle', horizontal: 'left' }
    cell.border = {
      right: { style: 'thick', color: { argb: '00000000' } }
    }
  })
  // 列头
  const notLeafNodeWidthMap: Record<string, number> = {}
  const { colLeafNodes } = layoutResult
  colLeafNodes.forEach(node => {
    let curNode = node.parent
    while (curNode) {
      const width = notLeafNodeWidthMap[curNode.id] ?? 0
      notLeafNodeWidthMap[curNode.id] = width + 1
      curNode = curNode.parent
    }
    const { colIndex } = node
    const writeRowIndex = node.level + 1
    const writeColIndex = colIndex + 1 + 1
    const cell = worksheet.getCell(writeRowIndex, writeColIndex)
    let value = node.label
    if (node.field === '$$extra$$' && metaMap[value]?.name) {
      value = metaMap[value].name
    }
    cell.value = value
    cell.alignment = { vertical: 'middle', horizontal: 'center' }
    if (writeRowIndex < maxColHeight) {
      worksheet.mergeCells(writeRowIndex, writeColIndex, maxColHeight, writeColIndex)
    }
    cell.border = {
      bottom: { style: 'thick', color: { argb: '00000000' } }
    }
  })
  const colNodes = layoutResult.colNodes
  const getNodeStartIndex = (node: Node) => {
    if (!node.children?.length) {
      return node.colIndex + 1
    } else {
      return getNodeStartIndex(node.children[0])
    }
  }
  colNodes.forEach(node => {
    if (node.isLeaf) {
      return
    }
    const colIndex = getNodeStartIndex(node)
    const width = notLeafNodeWidthMap[node.id]
    const writeRowIndex = node.level + 1
    const mergeRowCount = node.children[0].level - node.level
    const writeColIndex = colIndex + 1
    const cell = worksheet.getCell(writeRowIndex, writeColIndex)
    cell.value = node.label
    cell.alignment = { vertical: 'middle', horizontal: 'center' }
    if (mergeRowCount > 1 || width > 1) {
      worksheet.mergeCells(
        writeRowIndex,
        writeColIndex,
        writeRowIndex + mergeRowCount - 1,
        writeColIndex + width - 1
      )
    }
  })
  const formatterMap = chart.yAxis.reduce((p, n) => {
    if (n.dataeaseName) {
      p[n.dataeaseName] = n.formatterCfg
    }
    return p
  }, {})
  //  单元格数据
  for (let rowIndex = 0; rowIndex < rowLeafNodes.length; rowIndex++) {
    for (let colIndex = 0; colIndex < colLeafNodes.length; colIndex++) {
      const dataCellMeta = layoutResult.getCellMeta(rowIndex, colIndex)
      const { fieldValue } = dataCellMeta
      const cell = worksheet.getCell(rowIndex + maxColHeight + 1, colIndex + 1 + 1)
      cell.alignment = { vertical: 'middle', horizontal: 'center' }
      if (fieldValue === "-" || fieldValue === null || fieldValue === undefined) {
        cell.value = '-'
        continue
      }
      const meta = metaMap[dataCellMeta.valueField]
      const value = meta?.formatter?.(fieldValue) || fieldValue
      if (typeof value === 'number') {
        cell.value = value
      } else if (typeof value === 'string') {
        const formatterCfg = formatterMap?.[dataCellMeta.valueField]
        const result = extractNumber(value, formatterCfg)
        if (typeof result === 'string') {
          cell.value = result
        } else {
          cell.value = result.value
          cell.numFmt = result.numFmt
        }
      }
    }
  }
  const buffer = await workbook.xlsx.writeBuffer()
  const dataBlob = new Blob([buffer], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
  })
  saveAs(dataBlob, `${chart.title ?? '透视表'}.xlsx`)
}
 
export async function exportRowQuotaTreePivot(instance: PivotSheet, chart: ChartObj) {
  const layoutResult = instance.facet.layoutResult
  if (layoutResult.colLeafNodes.length + 1 > 16384) {
    ElMessage.warning(i18nt('chart.pivot_export_invalid_col_exceed'))
    return
  }
  const { meta, fields } = instance.dataCfg
  const colLength = fields?.columns?.length || 0
  const workbook = new Exceljs.Workbook()
  const worksheet = workbook.addWorksheet(i18nt('chart.chart_data'))
  const metaMap: Record<string, Meta> = meta?.reduce((p, n) => {
    if (n.field) {
      p[n.field] = n
    }
    return p
  }, {})
 
  // 角头
  fields.columns?.forEach((column, index) => {
    if (index >= fields.columns.length - 1) {
      return
    }
    const cell = worksheet.getCell(index + 1, 1)
    cell.value = metaMap[column]?.name ?? column
    cell.alignment = { vertical: 'middle', horizontal: 'center' }
    cell.border = {
      right: { style: 'thick', color: { argb: '00000000' } }
    }
  })
  const quotaColLabel = chart.customAttr.basicStyle.quotaColLabel ?? t('dataset.value')
  const maxColHeight = layoutResult.colsHierarchy.maxLevel + 1
  const rowName = fields?.rows
    ?.map(row => metaMap[row]?.name ?? row)
    .concat(quotaColLabel)
    .join('/')
  const cell = worksheet.getCell(colLength, 1)
  cell.value = rowName
  cell.alignment = { vertical: 'middle', horizontal: 'center' }
  cell.border = {
    right: { style: 'thick', color: { argb: '00000000' } },
    bottom: { style: 'thick', color: { argb: '00000000' } }
  }
  //行头
  const { rowLeafNodes } = layoutResult
  rowLeafNodes.forEach((node, index) => {
    const cell = worksheet.getCell(maxColHeight + index + 1, 1)
    let value = node.label
    if (node.field === '$$extra$$' && metaMap[value]?.name) {
      value = metaMap[value].name
    }
    cell.value = repeat('  ', node.level) + value
    cell.alignment = { vertical: 'middle', horizontal: 'left' }
    cell.border = {
      right: { style: 'thick', color: { argb: '00000000' } }
    }
  })
  // 列头
  const notLeafNodeWidthMap: Record<string, number> = {}
  const { colLeafNodes } = layoutResult
  colLeafNodes.forEach(node => {
    let curNode = node.parent
    while (curNode) {
      const width = notLeafNodeWidthMap[curNode.id] ?? 0
      notLeafNodeWidthMap[curNode.id] = width + 1
      curNode = curNode.parent
    }
    const { colIndex } = node
    const writeRowIndex = node.level + 1
    const writeColIndex = colIndex + 2
    const cell = worksheet.getCell(writeRowIndex, writeColIndex)
    cell.value = node.label
    cell.alignment = { vertical: 'middle', horizontal: 'center' }
    if (writeRowIndex < maxColHeight) {
      worksheet.mergeCells(writeRowIndex, writeColIndex, maxColHeight, writeColIndex)
    }
    cell.border = {
      bottom: { style: 'thick', color: { argb: '00000000' } }
    }
  })
  const colNodes = layoutResult.colNodes
  const getNodeStartIndex = (node: Node) => {
    if (!node.children?.length) {
      return node.colIndex + 1
    } else {
      return getNodeStartIndex(node.children[0])
    }
  }
  colNodes.forEach(node => {
    if (node.isLeaf) {
      return
    }
    const colIndex = getNodeStartIndex(node)
    const width = notLeafNodeWidthMap[node.id]
    const writeRowIndex = node.level + 1
    const writeColIndex = colIndex + 1
    const cell = worksheet.getCell(writeRowIndex, writeColIndex)
    cell.value = node.label
    cell.alignment = { vertical: 'middle', horizontal: 'center' }
    if (width > 1) {
      worksheet.mergeCells(writeRowIndex, writeColIndex, writeRowIndex, writeColIndex + width - 1)
    }
  })
  const formatterMap = chart.yAxis.reduce((p, n) => {
    if (n.dataeaseName) {
      p[n.dataeaseName] = n.formatterCfg
    }
    return p
  }, {})
  //  单元格数据
  for (let rowIndex = 0; rowIndex < rowLeafNodes.length; rowIndex++) {
    for (let colIndex = 0; colIndex < colLeafNodes.length; colIndex++) {
      const dataCellMeta = layoutResult.getCellMeta(rowIndex, colIndex)
      const { fieldValue } = dataCellMeta
      const cell = worksheet.getCell(rowIndex + maxColHeight + 1, colIndex + 2)
      cell.alignment = { vertical: 'middle', horizontal: 'center' }
      if (fieldValue === "-" || fieldValue === null || fieldValue === undefined) {
        cell.value = '-'
        continue
      }
      const meta = metaMap[dataCellMeta.valueField]
      const value = meta?.formatter?.(fieldValue) || fieldValue
      if (typeof value === 'number') {
        cell.value = value
      } else if (typeof value === 'string') {
        const formatterCfg = formatterMap?.[dataCellMeta.valueField]
        const result = extractNumber(value, formatterCfg)
        if (typeof result === 'string') {
          cell.value = result
        } else {
          cell.value = result.value
          cell.numFmt = result.numFmt
        }
      }
    }
  }
  const buffer = await workbook.xlsx.writeBuffer()
  const dataBlob = new Blob([buffer], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
  })
  saveAs(dataBlob, `${chart.title ?? '透视表'}.xlsx`)
}
 
function extractNumber(
  formattedValue: string,
  formatterCfg: BaseFormatter
):
  | {
      value: number
      numFmt: string
    }
  | string {
  if (!formatterCfg) {
    return formattedValue
  }
  let result = formattedValue
  if (formatterCfg.type === 'percent') {
    result = result.slice(0, -1) // 去掉百分号
    if (formatterCfg.thousandSeparator) {
      result = result.replace(/,/g, '')
    }
    //科学计数法
    if (result.includes('e')) {
      const valueArr = result.match(/^[+-]?\d+(\.\d+)?(e[+-]?\d+)?/)
      if (!valueArr?.length) {
        return formattedValue
      }
      const valueStr = valueArr[0]
      const value = parseFloat(valueStr)
      let numFmt = '0.'
      const number = valueStr.split('e')[0]
      numFmt += '0'.repeat(number.slice(1).length)
      numFmt += 'E+0"%"'
      return {
        value,
        numFmt
      }
    }
    const value = parseFloat(result) / 100
    let numFmt = '0'
    if (formatterCfg.decimalCount > 0) {
      numFmt += `.${'0'.repeat(formatterCfg.decimalCount)}`
    }
    numFmt += '%'
    return {
      value,
      numFmt
    }
  }
  if (formatterCfg.suffix) {
    const suffix = formatterCfg.suffix
    if (result.endsWith(suffix)) {
      result = result.slice(0, -suffix.length)
    }
  }
  if (formatterCfg.thousandSeparator) {
    result = result.replace(/,/g, '')
  }
  //科学计数法
  if (result.includes('e')) {
    const valueArr = result.match(/^[+-]?\d+(\.\d+)?(e[+-]?\d+)?/)
    if (!valueArr?.length) {
      return formattedValue
    }
    const valueStr = valueArr[0]
    const value = parseFloat(valueStr)
    let numFmt = '0.'
    const number = valueStr.split('e')[0]
    numFmt += '0'.repeat(number.slice(1).length)
    numFmt += 'E+0'
    const suffix = formattedValue.slice(valueStr.length)
    if (suffix) {
      numFmt += `"${suffix}"`
    }
    return {
      value,
      numFmt
    }
  }
  const valueArr = result.match(/^[+-]?\d+(\.\d+)?/)
  if (!valueArr?.length) {
    return formattedValue
  }
  const valueStr = valueArr[0]
  const value = parseFloat(valueStr)
  const unit = result.slice(valueStr.length)
  let numFmt = '#'
  if (formatterCfg.thousandSeparator) {
    numFmt += ',#'
  }
  if (Math.abs(value) < 1) {
    numFmt = '0'
  }
  if (formatterCfg.type === 'value') {
    if (formatterCfg.decimalCount > 0) {
      numFmt += `.${'0'.repeat(formatterCfg.decimalCount)}`
    }
  } else {
    if (valueStr.indexOf('.') > -1) {
      const decimalLength = valueStr.split('.')[1].length
      numFmt += `.${'0'.repeat(decimalLength)}`
    }
  }
  if (unit) {
    numFmt += `"${unit}"`
  }
  numFmt += `"${formatterCfg.suffix}"`
  return {
    value,
    numFmt
  }
}
 
export async function exportPivotExcel(instance: PivotSheet, chart: ChartObj) {
  const { fields } = instance.dataCfg
  const rowLength = fields?.rows?.length || 0
  const valueLength = fields?.values?.length || 0
  if (!(rowLength && valueLength)) {
    ElMessage.warning(i18nt('chart.pivot_export_invalid_field'))
    return
  }
  const { quotaPosition } = chart.customAttr.basicStyle
  if (chart.customAttr.basicStyle.tableLayoutMode !== 'tree') {
    if (quotaPosition === 'row') {
      exportRowQuotaGridPivot(instance, chart)
    } else {
      exportGridPivot(instance, chart)
    }
  } else {
    if (quotaPosition === 'row') {
      exportRowQuotaTreePivot(instance, chart)
    } else {
      exportTreePivot(instance, chart)
    }
  }
}
 
export function configMergeCells(chart: Chart, options: S2Options, dataConfig: S2DataConfig) {
  const { mergeCells } = parseJson(chart.customAttr).tableCell
  const { showIndex } = parseJson(chart.customAttr).tableHeader
  if (mergeCells) {
    options.frozenColCount = 0
    options.frozenRowCount = 0
    const fields = chart.data.fields || []
    const fieldsMap =
      fields.reduce((p, n) => {
        p[n.dataeaseName] = n
        return p
      }, {}) || {}
    const quotaIndex = dataConfig.meta.findIndex(m => fieldsMap[m.field]?.groupType === 'q')
    const data = chart.data?.tableRow
    if (quotaIndex === 0 || !data?.length) {
      return
    }
    const mergedColInfo: number[][][] = [[[0, data.length - 1]]]
    const mergedCellsInfo = []
    const axisToMerge = dataConfig.meta.filter((_, i) => i < quotaIndex || quotaIndex === -1)
    axisToMerge.forEach((a, i) => {
      if (mergedColInfo[i - 1]) {
        mergedColInfo[i - 1] = []
      }
      const preMergedColInfo = mergedColInfo[i]
      const curMergedColInfo = []
      mergedColInfo.push(curMergedColInfo)
      preMergedColInfo.forEach(range => {
        const [start, end] = range
        let lastVal = data[start][a.field]
        let lastIndex = start
        for (let index = start; index <= end; index++) {
          const curVal = data[index][a.field]
          if (curVal !== lastVal || index === end) {
            const curRange = index - lastIndex
            if (curRange > 1 || (index === end && curRange === 1 && lastVal === curVal)) {
              const tmpMergeCells = []
              let textIndex = curRange % 2 === 1 ? (curRange - 1) / 2 : curRange / 2 - 1
              if (index === end && lastVal === curVal) {
                textIndex = curRange % 2 === 1 ? (curRange - 1) / 2 : curRange / 2
              }
              for (let j = 0; j < curRange; j++) {
                tmpMergeCells.push({
                  colIndex: showIndex ? i + 1 : i,
                  rowIndex: lastIndex + j,
                  showText: j === textIndex
                })
              }
              if (index === end && lastVal === curVal) {
                tmpMergeCells.push({
                  colIndex: showIndex ? i + 1 : i,
                  rowIndex: index,
                  showText: false
                })
              }
              mergedCellsInfo.push(tmpMergeCells)
              curMergedColInfo.push([
                lastIndex,
                index === end && lastVal === curVal ? index : index - 1
              ])
            }
            lastVal = curVal
            lastIndex = index
          }
        }
      })
    })
    if (showIndex) {
      const indexMergedCells = mergedCellsInfo.filter(cells => cells[0].colIndex === 1)
      indexMergedCells.forEach(cells => {
        const tmpCells = cloneDeep(cells)
        tmpCells.forEach(cell => {
          cell.colIndex = 0
        })
        mergedCellsInfo.unshift(tmpCells)
      })
    }
    options.mergedCellsInfo = mergedCellsInfo
    options.mergedCell = (sheet, cells, meta) => {
      if (showIndex && meta.colIndex === 0) {
        meta.fieldValue = getRowIndex(mergedCellsInfo, meta)
      }
      meta.deFieldType = fieldsMap[meta.valueField]?.deType
      return new CustomMergedCell(sheet, cells, meta)
    }
  }
}
 
export function getRowIndex(mergedCellsInfo: MergedCellInfo[][], meta: ViewMeta): number {
  if (!mergedCellsInfo?.length) {
    return meta.rowIndex + 1
  }
  let curRangeStartIndex = meta.rowIndex
  const lostCells = mergedCellsInfo.reduce((p, n) => {
    if (n[0].colIndex !== 0) {
      return p
    }
    const start = n[0].rowIndex
    const end = n[n.length - 1].rowIndex
    const lost = end - start
    if (meta.rowIndex >= start && meta.rowIndex <= end) {
      curRangeStartIndex = start
    }
    if (meta.rowIndex > end) {
      return p + lost
    }
    return p
  }, 0)
  return curRangeStartIndex - lostCells + 1
}
 
class CustomMergedCell extends MergedCell {
  protected drawBackgroundShape() {
    const allPoints = getPolygonPoints(this.cells)
    // 处理条件样式,这里没有用透明度
    // 因为合并的单元格是单独的图层,透明度降低的话会显示底下未合并的单元格,需要单独处理被覆盖的单元格
    const { backgroundColor: fill } = this.getBackgroundColor()
    const cellTheme = this.theme.dataCell.cell
    this.backgroundShape = renderPolygon(this, {
      points: allPoints,
      stroke: cellTheme.horizontalBorderColor,
      fill,
      lineHeight: cellTheme.horizontalBorderWidth
    })
  }
 
 
  protected getTextStyle() {
    const textStyle = super.getTextStyle()
    const dataCellAlignConfig = this.theme.dataCellAlignConfig
    if (dataCellAlignConfig) {
      const align = dataCellAlignConfig[this.meta.valueField]
      if (align) {
        textStyle.textAlign = align
      }
    }
    if (textStyle.textAlign === 'custom') {
      textStyle.textAlign = 'left'
    }
    return textStyle
  }
 
  drawTextShape(): void {
    if (this.meta.deFieldType === 7) {
      drawImage.apply(this)
    } else {
      super.drawTextShape()
    }
  }
}
 
export class CustomDataCell extends TableDataCell {
  /**
   * 重写这个方法是为了处理底部的汇总行取消 hover 状态时设置 border 为 1,
   * 这样会导致单元格隐藏横边边框失败,出现一条白线
   */
  hideInteractionShape() {
    this.stateShapes.forEach(shape => {
      updateShapeAttr(shape, SHAPE_STYLE_MAP.backgroundOpacity, 0)
      updateShapeAttr(shape, SHAPE_STYLE_MAP.backgroundColor, 'transparent')
      updateShapeAttr(shape, SHAPE_STYLE_MAP.borderOpacity, 0)
      updateShapeAttr(shape, SHAPE_STYLE_MAP.borderWidth, 0)
      updateShapeAttr(shape, SHAPE_STYLE_MAP.borderColor, 'transparent')
    })
  }
 
  public getBackgroundColor() {
    let bgColorInfo = super.getBackgroundColor()
    if (this.meta.isMergedCell) {
      bgColorInfo = {
        ...bgColorInfo,
        backgroundColorOpacity: 0
      }
    }
    return bgColorInfo
  }
 
  protected getTextStyle() {
    const textStyle = super.getTextStyle()
    const dataCellAlignConfig = this.theme.dataCellAlignConfig
    if (dataCellAlignConfig) {
      const align = dataCellAlignConfig[this.meta.valueField]
      if (align) {
        textStyle.textAlign = align
      }
    }
    if (textStyle.textAlign === 'custom') {
      textStyle.textAlign = 'left'
    }
    return textStyle
  }
 
  /**
   * 重写绘制文本内容的方法
   * @protected
   */
  protected drawTextShape() {
    if(this.meta.isMergedCell) {
      return
    }
    if (this.meta.autoWrap) {
      drawTextShape(this, false)
    } else {
      super.drawTextShape()
    }
  }
}
 
export class CustomTableColCell extends TableColCell {
 
  protected getTextStyle() {
    const textStyle = super.getTextStyle()
    const colCellAlignConfig = this.theme.colCellAlignConfig
    if (colCellAlignConfig) {
      // 分组单元格居中
      if (this.meta.children?.length) {
        textStyle.textAlign = 'center'
        return textStyle
      }
      const align = colCellAlignConfig[this.meta.field]
      if (align) {
        textStyle.textAlign = align
      }
    }
    if (textStyle.textAlign === 'custom') {
      textStyle.textAlign = 'left'
    }
    return textStyle
  }
 
  /**
   * 重写是为了表头文本内容的换行
   * @protected
   */
  protected drawTextShape() {
    if (this.meta.autoWrap) {
      drawTextShape(this, true)
    } else {
      super.drawTextShape()
    }
  }
}
 
/**
 * 绘制文本 换行
 * @param cell
 * @param isHeader
 */
const drawTextShape = (cell, isHeader) => {
  // 换行符
  const lineBreak = '\n'
  // 省略号
  const ellipsis = '...'
  // 用户配置的最大行数
  const maxLines = cell.meta.maxLines ?? 1
  const {
    options: { placeholder }
  } = cell.spreadsheet
  const emptyPlaceholder = getEmptyPlaceholder(this, placeholder)
  // 单元格文本
  const { formattedValue } = cell.getFormattedFieldValue()
  // 获取文本样式
  const textStyle = cloneDeep(cell.getTextStyle())
  textStyle.textAlign = undefined
  // 宽度能放几个字符,就放几个,放不下就换行
  let wrapText = getWrapText(
    formattedValue ? formattedValue?.toString() : emptyPlaceholder,
    textStyle,
    cell.meta.width,
    cell.spreadsheet
  )
  const lines = wrapText.split(lineBreak)
  let extraStyleFontSize = textStyle.fontSize
  // 不是表头,处理文本高度和换行
  if (!isHeader) {
    const textHeight = getWrapTextHeight(
      wrapText.replaceAll(lineBreak, ''),
      textStyle,
      cell.spreadsheet,
      maxLines
    )
    const lineCountInCell = Math.floor(cell.meta.height / textHeight)
    const wrapTextArr = lines.slice(0, lineCountInCell)
 
    // 根据行数调整换行后的文本内容
    wrapText = lineCountInCell < 1 ? ellipsis : wrapTextArr.join(lineBreak) || ellipsis
    const resultWrapArr = wrapText.split(lineBreak)
    // 控制最大行数
    if (
      !wrapText.endsWith(ellipsis) &&
      (lines.length > maxLines || lines.length > lineCountInCell)
    ) {
      // 第一行的字符个数
      const firstLineStrNumber = resultWrapArr[0].length
      const temp = resultWrapArr.slice(0, Math.min(maxLines, lineCountInCell))
      // 修改最后一行的字符,按照第一行字符个数-1,修改最后一行的字符为...
      temp[temp.length - 1] = temp[temp.length - 1].slice(0, firstLineStrNumber - 1) + ellipsis
      wrapText = temp.join(lineBreak)
    }
    if (wrapText === ellipsis) {
      extraStyleFontSize = 12
    }
  } else {
    const resultWrapArr = wrapText.split(lineBreak)
    // 控制最大行数
    if (lines.length > maxLines) {
      const temp = resultWrapArr.slice(0, maxLines)
      // 第一行的字符个数
      const firstLineStrNumber = resultWrapArr[0].length
      // 修改最后一行的字符
      temp[temp.length - 1] = temp[temp.length - 1].slice(0, firstLineStrNumber - 1) + ellipsis
      wrapText = temp.join(lineBreak)
    }
  }
  // 设置最终文本和其宽度
  cell.actualText = wrapText
  cell.actualTextWidth = cell.spreadsheet.measureTextWidth(wrapText, textStyle)
 
  // 获取文本位置并渲染文本
  const { y } = cell.getTextAndIconPosition()?.text || cell.getTextPosition()
  const x = getTextStartX(cell, textStyle)
  // 绘制文本
  cell.textShape = renderText(cell, [cell.textShape], x, y, wrapText, textStyle, {
    fontSize: extraStyleFontSize
  })
 
  // 将文本形状添加到形状数组
  cell.textShapes.push(cell.textShape)
}
 
/**
 * 计算文本起始X位置
 * @param cell
 * @param textStyle
 */
function getTextStartX(cell, textStyle) {
  // 获取单元格区域
  const area = cell.getCellArea()
  // 计算文本宽度,只计算第一行宽度
  const textWidth = cell.spreadsheet.measureTextWidthRoughly(
    cell.actualText.split('\n')[0],
    textStyle
  )
  const padding = cell.theme.colCell?.cell?.padding ?? { left: 0, right: 0 }
  const align = cell.getTextStyle()?.textAlign ?? 'left'
  const paddingLeft = padding.left || 0
  const paddingRight = padding.right || 0
  // 可用宽度(扣除 padding)
  const availableWidth = area.width - paddingLeft - paddingRight
  switch (align) {
    case 'left':
      return area.x + paddingLeft
    case 'center':
      return area.x + paddingLeft + (availableWidth - textWidth) / 2
    case 'right':
      return area.x + area.width - textWidth - paddingRight
    default:
      return area.x + paddingLeft
  }
}
 
/**
 * 计算表头高度
 * @param info 单元格信息
 * @param newChart
 * @param tableHeader 表头配置
 * @param basicStyle 表格基础样式
 * @param layoutResult
 */
export const calculateHeaderHeight = (info, newChart, tableHeader, basicStyle, layoutResult) => {
  if (tableHeader.showTableHeader === false) return
  const ev = layoutResult || newChart.facet.layoutResult
  const maxLines = basicStyle.maxLines ?? 1
  const textStyle = { ...newChart.theme.cornerCell.text }
  const sourceText = info.info.meta.value
  let maxHeight = getWrapTextHeight(
    getWrapText(sourceText, textStyle, info.info.resizedWidth, ev.spreadsheet),
    textStyle,
    ev.spreadsheet,
    maxLines
  )
 
  // 获取最大高度的列,排除当前列
  const maxHeightCol = ev.colLeafNodes
    .filter(n => n.colIndex !== info.info.meta.colIndex)
    .reduce(
      (maxHeightNode, currentNode) => {
        const wrapTextHeight = getWrapTextHeight(
          getWrapText(currentNode.value, textStyle, currentNode.width, currentNode.spreadsheet),
          textStyle,
          currentNode.spreadsheet,
          maxLines
        )
        return wrapTextHeight > maxHeightNode.height
          ? { height: wrapTextHeight, colIndex: currentNode.colIndex }
          : maxHeightNode
      },
      { height: 0 }
    )
 
  // 使用最大高度
  maxHeight = Math.max(maxHeight, maxHeightCol.height) + textStyle.fontSize + 10.5
 
  if (layoutResult) {
    if (basicStyle.tableColumnMode === 'adapt') maxHeight -= textStyle.fontSize - 2
    ev.colLeafNodes.forEach(n => (n.height = maxHeight))
    ev.colsHierarchy.height = maxHeight
  }
}
 
/**
 * 获取换行文本
 * 累加字符串单个字符的宽度,超过单元格宽度时,添加换行
 * @param sourceText
 * @param textStyle
 * @param cellWidth
 * @param spreadsheet
 */
const getWrapText = (sourceText, textStyle, cellWidth, spreadsheet) => {
  if (!sourceText && sourceText !== 0) return ''
  sourceText = sourceText.toString().trim()
  const getTextWidth = text => spreadsheet.measureTextWidthRoughly(text, textStyle)
 
  let resultWrapText = ''
  let restText = ''
  let restTextWidth = 0
  for (let i = 0; i < sourceText.length; i++) {
    const char = sourceText[i]
    const charWidth = getTextWidth(char)
    restTextWidth += charWidth
    restText += char
    // 中文时,需要单元格宽度减去16个文字宽度,否则会超出单元格宽度
    const cWidth = char.charCodeAt(0) >= 128 ? 12 : 8
    // 添加换行
    if (restTextWidth >= cellWidth - textStyle.fontSize - cWidth) {
      // 最后一个字符不添加换行符
      resultWrapText += restText + (i !== sourceText.length - 1 ? '\n' : '')
      restText = ''
      restTextWidth = 0
    }
  }
 
  resultWrapText += restText
  return resultWrapText
}
/**
 * 计算文本行高
 * @param wrapText
 * @param textStyle
 * @param spreadsheet
 * @param maxLines 最大行数
 */
const getWrapTextHeight = (wrapText, textStyle, spreadsheet, maxLines) => {
  // 行内最高
  let maxHeight = 0
  // 获取最高字符的高度
  for (const char of wrapText) {
    const h = textStyle.fontSize / (char.charCodeAt(0) >= 128 ? 5 : 2.5)
    maxHeight = Math.max(maxHeight, spreadsheet.measureTextHeight(char, textStyle) + h)
  }
  // 行数
  const lines = wrapText.split('\n').length
  return Math.min(lines, maxLines) * maxHeight
}
 
// 导出获取汇总行的函数
export function getSummaryRow(data, axis, sumCon = [], customSumResult = {}) {
  const summaryObj = { SUMMARY: true }
  for (let i = 0; i < axis.length; i++) {
    const a = axis[i].dataeaseName
    let savedAxis = find(sumCon, s => s.field === a)
    if (savedAxis) {
      if (savedAxis.summary == undefined) {
        savedAxis.summary = 'sum' // 默认汇总方式为求和
      }
      if (savedAxis.show == undefined) {
        savedAxis.show = true // 默认显示汇总结果
      }
    } else {
      savedAxis = {
        field: a,
        summary: 'sum',
        show: true
      }
    }
    // 如果配置为不显示,则跳过该字段
    if (!savedAxis.show) {
      continue
    }
    // 根据汇总方式处理数据
    switch (savedAxis.summary) {
      case 'sum':
        // 计算字段的总和
        summaryObj[a] = safeDecimalSum(data, a)
        break
      case 'avg':
        // 计算字段的平均值
        summaryObj[a] = safeDecimalMean(data, a)
        break
      case 'max':
        // 计算字段的最大值
        summaryObj[a] = maxBy(
          filter(data, d => parseFloat(d[a]) !== undefined),
          d => parseFloat(d[a]) // 提取数值
        )[a]
        break
      case 'min':
        // 计算字段的最小值
        summaryObj[a] = minBy(
          filter(data, d => parseFloat(d[a]) !== undefined),
          d => parseFloat(d[a]) // 提取数值
        )[a]
        break
      case 'var_pop':
        // 计算总体方差(需要至少2个数据点)
        if (data.length < 2) {
          continue
        } else {
          const mean = safeDecimalMean(data, a) // 计算平均值
          // 计算每个数据点与平均值的差的平方
          const squaredDeviations = map(data, d => {
            const value = new Decimal(d[a] ?? 0) // 获取字段值,如果不存在则使用0
            const dev = value.minus(mean) // 计算差值
            return dev.times(dev) // 计算平方
          })
          // 计算方差(平方差的平均值)
          const variance = squaredDeviations.reduce((acc, val) => acc.plus(val), new Decimal(0))
          summaryObj[a] = variance.dividedBy(data.length - 1).toNumber() // 计算总体方差
        }
        break
      case 'stddev_pop':
        // 计算总体标准差(需要至少2个数据点)
        if (data.length < 2) {
          continue
        } else {
          const mean = safeDecimalMean(data, a) // 计算平均值
          // 计算每个数据点与平均值的差的平方
          const squaredDeviations = map(data, d => {
            const value = new Decimal(d[a] ?? 0) // 获取字段值,如果不存在则使用0
            const dev = value.minus(mean) // 计算差值
            return dev.times(dev) // 计算平方
          })
          // 计算方差(平方差的平均值)
          const variance = squaredDeviations.reduce((acc, val) => acc.plus(val), new Decimal(0))
          summaryObj[a] = variance
            .dividedBy(data.length - 1)
            .sqrt()
            .toNumber() // 计算总体标准差
        }
        break
      case 'custom':
        summaryObj[a] = customSumResult[a]
        break
    }
  }
 
  // 返回汇总结果对象
  return summaryObj
}
 
export class SummaryCell extends CustomDataCell {
  getTextStyle() {
    const textStyle = cloneDeep(this.theme.colCell.bolderText)
    const dataCellAlignConfig = this.theme.dataCellAlignConfig
    if (dataCellAlignConfig) {
      const align = dataCellAlignConfig[this.meta.valueField]
      if (align) {
        textStyle.textAlign = align
      }
    } else {
      textStyle.textAlign = this.theme.dataCell.text.textAlign
    }
    return textStyle
  }
 
  getBackgroundColor() {
    const { backgroundColor, backgroundColorOpacity } = this.theme.colCell.cell
    return { backgroundColor, backgroundColorOpacity }
  }
}
 
/**
 * 配置空数据样式
 * @param newChart
 * @param basicStyle
 * @param newData
 * @param container
 */
export const configEmptyDataStyle = (newChart, basicStyle, newData, container) => {
  /**
   * 辅助函数:移除空数据dom
   */
  const removeEmptyDom = () => {
    const emptyElement = document.getElementById(container + '_empty')
    if (emptyElement) {
      emptyElement.parentElement.removeChild(emptyElement)
    }
  }
  removeEmptyDom()
  if (newData.length) return
  newChart.on(S2Event.LAYOUT_AFTER_HEADER_LAYOUT, ev => {
    removeEmptyDom()
    if (!newData.length) {
      const emptyDom = document.createElement('div')
      const left = Math.min(newChart.options.width, ev.colsHierarchy.width) / 2 - 32
      emptyDom.id = container + '_empty'
      emptyDom.textContent = i18nt('data_set.no_data')
      emptyDom.setAttribute(
        'style',
        `position: absolute;
        left: ${left}px;
        top: 50%;`
      )
      const parent = document.getElementById(container)
      parent.insertBefore(emptyDom, parent.firstChild)
    }
  })
}
 
export const getLeafNodes = (tree: Array<ColumnNode>): ColumnNode[] => {
  const result: ColumnNode[] = []
  const inorderTraversal = node => {
    if (!node.children?.length) {
      // 叶子节点,添加到结果数组
      result.push(node)
      return
    }
    // 中序遍历
    for (let i = 0; i < node.children?.length; i++) {
      inorderTraversal(node.children[i])
    }
  }
 
  // 遍历树中所有节点
  tree.forEach(node => inorderTraversal(node))
  return result
}
 
export const getColumns = (fields, cols: Array<ColumnNode>) => {
  const result = []
  for (let i = 0; i < cols.length; i++) {
    if (fields.includes(cols[i].key)) {
      result.push(cols[i])
    }
    if (cols[i].children?.length) {
      result.push(...getColumns(fields, cols[i].children as Array<ColumnNode>))
    }
  }
  return result
}
 
export function drawImage() {
  const img = new Image()
  const { x, y, width, height, fieldValue } = this.meta
  img.src = fieldValue as string
  img.setAttribute('crossOrigin', 'anonymous')
  img.onload = () => {
    !this.cfg.children && (this.cfg.children = [])
    const { width: imgWidth, height: imgHeight } = img
    const ratio = Math.max(imgWidth / width, imgHeight / height)
    // 不铺满,部分留白
    const imgShowWidth = (imgWidth / ratio) * 0.8
    const imgShowHeight = (imgHeight / ratio) * 0.8
    this.textShape = this.addShape('image', {
      attrs: {
        x: x + (imgShowWidth < width ? (width - imgShowWidth) / 2 : 0),
        y: y + (imgShowHeight < height ? (height - imgShowHeight) / 2 : 0),
        width: imgShowWidth,
        height: imgShowHeight,
        img
      }
    })
  }
}
 
export function calcTreeWidth(node) {
  if (!node.children?.length) {
    return node.width
  }
  return node.children.reduce((pre, cur) => {
    return pre + calcTreeWidth(cur)
  }, 0)
}
 
export function getStartPosition(node) {
  if (!node.children?.length) {
    return node.x
  }
  return getStartPosition(node.children[0])
}
 
function getMaxTreeDepth(nodes) {
  if (!nodes?.length) {
    return 0
  }
  return Math.max(
    ...nodes.map(node => {
      if (!node.children?.length) {
        return 1
      }
      return getMaxTreeDepth(node.children) + 1
    })
  )
}
 
export function summaryRowStyle(newChart, newData, tableCell, tableHeader, showSummary) {
  if (!showSummary || !newData.length) return
  const columns = newChart.dataCfg.fields.columns
  const showHeader = tableHeader.showTableHeader === true
  // 不显示表头时,减少一个表头的高度
  const headerAndSummaryHeight = showHeader ? getMaxTreeDepth(columns) + 1 : 1
  newChart.on(S2Event.LAYOUT_BEFORE_RENDER, () => {
    const totalHeight =
      tableHeader.tableTitleHeight * headerAndSummaryHeight +
      tableCell.tableItemHeight * (newData.length - 1)
    if (totalHeight < newChart.container.cfg.height) {
      newChart.options.height =
        totalHeight < newChart.container.cfg.height - 8 ? totalHeight + 8 : totalHeight
    }
  })
}
 
/**
 * 计算分组表头高度
 * @param newChart
 * @param tableHeader
 * @param basicStyle
 */
export const calculateGroupHeaderHeight = (newChart, tableHeader, basicStyle) => {
  let maxGroupHeight = 0
  // 获取分组名字最长的列
  const maxNameMeta = newChart.dataCfg?.meta
    ?.filter(item => !item.field.startsWith('f_'))
    ?.reduce((max, cur) => (cur.name.length > (max?.name.length ?? 0) ? cur : max), null)
  if (maxNameMeta) {
    let colWidth = basicStyle.tableColumnWidth
    const maxNameColumn = findNodeByKey(newChart.dataCfg.fields.columns, maxNameMeta.field)
    const maxNameColumns = []
    if (maxNameColumn) {
      maxNameColumns.push(maxNameColumn)
    }
    const { resizedWidth, meta } = newChart.store.get('resizeColWidthInfo') || {
      resizedWidth: 0,
      width: 0
    }
    const leafKeys = getLeafKeys(maxNameColumns)
    if (basicStyle.tableFieldWidth.length > 0) {
      colWidth = 0
      const fieldWidth = basicStyle.tableFieldWidth
      // fieldWidth中对象的key在leafKeys时,对fieldWidth中对象的width求和
      fieldWidth.forEach(fw => {
        // 调整单元格宽度时,排除掉当前调整的列,使用调整后的宽度
        if (
          leafKeys.filter(key => meta?.key !== key).includes(fw.fieldId) &&
          isNumber(fw.width) &&
          fw.width > 0
        ) {
          colWidth += fw.width
        }
      })
    }
    if (basicStyle.tableColumnMode === 'custom') {
      colWidth = basicStyle.tableColumnWidth * (leafKeys.length === 0 ? 1 : leafKeys.length) || 100
    } else {
      colWidth =
        (newChart.facet?.cfg?.width ? newChart.facet.cfg.width : newChart.options.width) *
        (colWidth / 100)
    }
    // 计算分组表头的高度
    if (colWidth > 0) {
      colWidth = colWidth + resizedWidth
      const nodeHeight = calculateGroupHeaderMaxTextHeight(
        { info: { name: maxNameMeta.name, resizedWidth: colWidth } },
        newChart,
        tableHeader,
        basicStyle,
        null
      )
      maxGroupHeight = Math.max(maxGroupHeight, nodeHeight)
    }
    if (maxGroupHeight > 0) {
      newChart.options.style.colCfg.height = maxGroupHeight
    }
  }
}
 
// 获取最里层的叶子节点
const getLeafKeys = (columns: any[]): string[] => {
  const keys: string[] = []
  columns.forEach(col => {
    if (col && typeof col === 'object' && Array.isArray(col.children) && col.children.length > 0) {
      keys.push(...getLeafKeys(col.children))
    } else if (col && typeof col === 'object' && col.key) {
      keys.push(col.key)
    }
  })
  return keys
}
// 根据 key 查找节点
const findNodeByKey = (columns: any[], key: string): any | null => {
  for (const col of columns) {
    if (col.key === key) return col
    if (col.children) {
      const found = findNodeByKey(col.children, key)
      if (found) return found
    }
  }
  return null
}
 
/**
 * 计算分组表头最大文本高度
 * @param info
 * @param newChart
 * @param tableHeader
 * @param basicStyle
 * @param _layoutResult
 */
const calculateGroupHeaderMaxTextHeight = (
  info,
  newChart,
  tableHeader,
  basicStyle,
  _layoutResult
) => {
  if (tableHeader.showTableHeader === false) return
  const maxLines = basicStyle.maxLines ?? 1
  const textStyle = { ...newChart.theme.cornerCell.text, fontSize: tableHeader.tableTitleFontSize }
  const sourceText = info.info.name
  return (
    getWrapTextHeight(
      getWrapText(sourceText, textStyle, info.info.resizedWidth, newChart),
      textStyle,
      newChart,
      maxLines
    ) +
    textStyle.fontSize +
    10.5
  )
}
 
export const isNumeric = (value: any): boolean => {
  return !isNaN(parseFloat(value)) && isFinite(value)
}