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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/*
Copyright (c) 2025 Tethys Plex

This file is part of Veloera.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import {
  API,
  copy,
  isMobile,
  shouldShowPrompt,
  showError,
  showInfo,
  showSuccess,
  showWarning,
  timestamp2string,
} from '../helpers';

import { CHANNEL_OPTIONS, ITEMS_PER_PAGE } from '../constants';
import {
  getQuotaPerUnit,
  renderGroup,
  renderNumberWithPoint,
  renderQuota,
  renderQuotaWithPrompt,
  stringToColor,
} from '../helpers/render';
import {
  Button,
  Divider,
  Dropdown,
  Form,
  Input,
  InputNumber,
  Modal,
  Popconfirm,
  Space,
  SplitButtonGroup,
  Switch,
  Table,
  Tag,
  Tooltip,
  Typography,
  Checkbox,
  Layout,
} from '@douyinfe/semi-ui';
import EditChannel from '../pages/Channel/EditChannel';
import {
  IconList,
  IconTreeTriangleDown,
  IconClose,
  IconFilter,
  IconPlus,
  IconRefresh,
  IconSetting,
  IconCopy,
} from '@douyinfe/semi-icons';
import { loadChannelModels } from './utils.js';
import EditTagModal from '../pages/Channel/EditTagModal.js';
import TextNumberInput from './custom/TextNumberInput.js';
import { useTranslation } from 'react-i18next';

function renderTimestamp(timestamp) {
  return <>{timestamp2string(timestamp)}</>;
}

// 辅助函数:获取失败的模型统计
const getFailedModelsStats = (batchTestResults, currentModels = null) => {
  // 如果提供了当前模型列表,只统计当前模型中的失败情况
  const currentModelSet = currentModels ? new Set(currentModels.split(',').map(m => m.trim()).filter(m => m)) : null;
  
  // 过滤测试结果:只保留当前模型中的结果
  const relevantResults = currentModelSet 
    ? batchTestResults.filter(r => currentModelSet.has(r.model))
    : batchTestResults;
  
  // 优化性能:只遍历一次,先获取所有失败的模型
  const failedModels = relevantResults.filter(r => !r.success);
  // 然后从失败模型中过滤出可重试的,避免第二次完整遍历
  const retryableFailedModels = failedModels.filter(r => r.isRetryable);
  
  return {
    failed: failedModels,
    retryable: retryableFailedModels,
    failedCount: failedModels.length,
    retryableCount: retryableFailedModels.length
  };
};

// 辅助函数:处理模型列表数据
const processModelData = (
  models,
  searchKeyword,
  batchTestResults,
  isBatchTesting,
  currentTestingModel,
  testingModelsSet = null
) => {
  if (!models) return [];
  
  // 优化性能:将测试结果转换为 Map,查找时间复杂度从 O(N) 降低到 O(1)
  const testResultsMap = new Map(batchTestResults.map(result => [result.model, result]));
  
  return models
    .split(',')
    .map(model => model.trim())
    .filter(model => model && model.toLowerCase().includes(searchKeyword.toLowerCase()))
    .map((model, index) => {
      const testResult = testResultsMap.get(model);
      return {
        key: model,
        model: model,
        testResult: testResult,
        isSuccess: testResult?.success,
        isFailed: testResult && !testResult.success,
        isTesting: isBatchTesting
         ? currentTestingModel.includes(model)
         : Boolean(testingModelsSet && testingModelsSet.has(model)),
        isRetryable: testResult?.isRetryable
      };
    });
};

// 模型测试内容组件
const ModelTestContent = ({ 
  channel, 
  isBatchTesting, 
  concurrentLimit, 
  setConcurrentLimit,
  testAllModels,
  modelSearchKeyword,
  setModelSearchKeyword,
  batchTestResults,
  retryFailedModels,
  handleDeleteFailedModels,
  testProgress,
  currentTestingModel,
  testChannel,
  showSuccess,
  showError,
  t 
}) => {
  const failedStats = getFailedModelsStats(batchTestResults, channel.models);
  
  // 追踪单个模型测试状态
  const [testingModels, setTestingModels] = React.useState(() => new Set());
  
  // 单个模型测试函数
  const runSingleTest = async (model) => {
    setTestingModels(prev => {
      const next = new Set(prev);
      next.add(model);
      return next;
    });
    try {
      await testChannel(channel, model);
    } finally {
      setTestingModels(prev => {
        const next = new Set(prev);
        next.delete(model);
        return next;
      });
    }
  };
  
  // 使用 useMemo 缓存模型数据处理结果
  const modelData = React.useMemo(() => processModelData(
    channel.models,
    modelSearchKeyword,
    batchTestResults,
    isBatchTesting,
    currentTestingModel,
    testingModels
  ), [channel.models, modelSearchKeyword, batchTestResults, isBatchTesting, currentTestingModel, testingModels]);

  return (
    <div>
      {/* 渠道信息和操作按钮 */}
      <div style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        padding: '16px 0',
        borderBottom: '1px solid var(--semi-color-border)',
        marginBottom: '16px'
      }}>
        <Typography.Title heading={6} style={{ margin: 0 }}>
          {t('渠道')}: {channel.name}
        </Typography.Title>
        
        {/* 主要操作按钮组 */}
        <div style={{ 
          display: 'flex', 
          alignItems: 'center',
          gap: '12px'
        }}>
          {!isBatchTesting && (
            <>
              <Typography.Text style={{ fontSize: '14px' }}>
                {t('并发测试模型数')}:
              </Typography.Text>
              <InputNumber
                value={concurrentLimit}
                onChange={setConcurrentLimit}
                min={1}
                max={10}
                style={{ width: '80px' }}
                size='small'
              />
            </>
          )}
          
          <Button
            type='primary'
            loading={isBatchTesting}
            onClick={testAllModels}
            disabled={!channel?.models}
          >
            {isBatchTesting ? t('测试中...') : t('测试全部')}
          </Button>
        </div>
      </div>

      {/* 搜索框和操作按钮 */}
      <div style={{ 
        display: 'flex', 
        alignItems: 'center', 
        marginBottom: '16px',
        gap: '12px'
      }}>
        <Input
          placeholder={t('搜索模型...')}
          value={modelSearchKeyword}
          onChange={(v) => setModelSearchKeyword(v)}
          prefix={<IconFilter />}
          showClear
          style={{ flex: 1 }}
        />
        
        {/* 失败模型处理按钮组 */}
        {batchTestResults.length > 0 && failedStats.failedCount > 0 && (
          <div style={{ 
            display: 'flex',
            gap: '8px', 
            alignItems: 'center'
          }}>
            {failedStats.retryableCount > 0 && (
              <Button
                type='warning'
                loading={isBatchTesting}
                onClick={retryFailedModels}
                disabled={isBatchTesting}
              >
                {isBatchTesting ? t('重试中...') : t('重试失败 ({{count}})', { count: failedStats.retryableCount })}
              </Button>
            )}

            <Button
              type='danger'
              onClick={() => handleDeleteFailedModels(failedStats.failed)}
            >
              {t('删除失败 ({{count}})', { count: failedStats.failedCount })}
            </Button>
          </div>
        )}
      </div>

      {/* 测试进度显示 */}
      {isBatchTesting && (
        <div style={{ marginBottom: '16px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
            <Typography.Text style={{ fontSize: '14px' }}>
              {t('进度')}: {testProgress.completed}/{testProgress.total}
            </Typography.Text>
            <div style={{
              flex: 1,
              height: '6px',
              backgroundColor: 'var(--semi-color-fill-1)',
              borderRadius: '3px',
              overflow: 'hidden'
            }}>
              <div style={{
                width: `${testProgress.total > 0 ? (testProgress.completed / testProgress.total) * 100 : 0}%`,
                height: '100%',
                backgroundColor: 'var(--semi-color-primary)',
                borderRadius: '3px',
                transition: 'width 0.3s ease'
              }} />
            </div>
          </div>
          {currentTestingModel && (
            <Typography.Text style={{ 
              fontSize: '12px',
              color: 'var(--semi-color-text-1)'
            }}>
              {t('正在测试')}: {currentTestingModel.includes(':') ? currentTestingModel.split(':').slice(1).join(':').trim() : currentTestingModel}
            </Typography.Text>
          )}
        </div>
      )}

      {/* 模型测试表格 */}
      <Table
        dataSource={modelData}
        columns={[
          {
            title: t('模型名称'),
            dataIndex: 'model',
            key: 'model',
            width: '40%',
            render: (text, record) => (
              <Typography.Text
                style={{
                  fontWeight: '500',
                  color: record.testResult ? 
                    (record.isSuccess ? 'var(--semi-color-success)' : 'var(--semi-color-danger)') : 
                    'var(--semi-color-text-0)',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis'
                }}
                ellipsis={{ showTooltip: true }}
              >
                {text}
              </Typography.Text>
            )
          },
          {
            title: t('状态'),
            key: 'status',
            width: '20%',
            render: (_, record) => {
              if (record.isTesting) {
                return <Tag color='blue'>{t('测试中')}</Tag>;
              }
              if (record.testResult) {
                return (
                  <Tag color={record.isSuccess ? 'green' : 'red'}>
                    {record.isSuccess ? t('成功') : t('失败')}
                  </Tag>
                );
              }
              return <Tag color='default'>{t('未测试')}</Tag>;
            }
          },
          {
            title: t('耗时'),
            key: 'duration',
            width: '15%',
            render: (_, record) => {
              if (record.testResult?.time) {
                return (
                  <Typography.Text style={{ color: 'var(--semi-color-text-1)' }}>
                    {record.testResult.time.toFixed(2)}s
                  </Typography.Text>
                );
              }
              return '-';
            }
          },
          {
            title: t('操作'),
            key: 'actions',
            width: '25%',
            render: (_, record) => (
              <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                <Button
                  size='small'
                  loading={record.isTesting}
                  onClick={() => runSingleTest(record.model)}
                >
                  {record.isTesting ? t('测试中') : t('测试')}
                </Button>
                <Button
                  size='small'
                  icon={<IconCopy />}
                  onClick={async () => {
                    const success = await copy(record.model);
                    if (success) {
                      showSuccess(t('模型名称已复制'));
                    } else {
                      showError(t('复制失败'));
                    }
                  }}
                />
              </div>
            )
          }
        ]}
        pagination={false}
        size='small'
        style={{ marginBottom: '25px' }}
      />

      {/* 显示搜索结果数量 */}
      {modelSearchKeyword && (
        <div style={{ marginTop: '16px' }}>
          <Typography.Text style={{ 
            display: 'block',
            fontSize: '14px',
            textAlign: 'center',
            color: 'var(--semi-color-text-1)'
          }}>
            {t('找到 {{count}} 个模型', { count: modelData.length })}
          </Typography.Text>
        </div>
      )}
    </div>
  );
};

const ChannelsTable = () => {
  const { t } = useTranslation();

  let type2label = undefined;

  const renderType = (type) => {
    if (!type2label) {
      type2label = new Map();
      for (let i = 0; i < CHANNEL_OPTIONS.length; i++) {
        type2label[CHANNEL_OPTIONS[i].value] = CHANNEL_OPTIONS[i];
      }
      type2label[0] = { value: 0, label: t('未知类型'), color: 'grey' };
    }
    return (
      <Tag size='large' color={type2label[type]?.color}>
        {type2label[type]?.label}
      </Tag>
    );
  };

  const renderTagType = () => {
    return (
      <Tag
        color='light-blue'
        prefixIcon={<IconList />}
        size='large'
        shape='circle'
        type='light'
      >
        {t('标签聚合')}
      </Tag>
    );
  };

  const renderStatus = (status) => {
    switch (status) {
      case 1:
        return (
          <Tag size='large' color='green'>
            {t('已启用')}
          </Tag>
        );
      case 2:
        return (
          <Tag size='large' color='yellow'>
            {t('已禁用')}
          </Tag>
        );
      case 3:
        return (
          <Tag size='large' color='yellow'>
            {t('自动禁用')}
          </Tag>
        );
      default:
        return (
          <Tag size='large' color='grey'>
            {t('未知状态')}
          </Tag>
        );
    }
  };

  const renderResponseTime = (responseTime) => {
    let time = responseTime / 1000;
    time = time.toFixed(2) + t(' 秒');
    if (responseTime === 0) {
      return (
        <Tag size='large' color='grey'>
          {t('未测试')}
        </Tag>
      );
    } else if (responseTime <= 1000) {
      return (
        <Tag size='large' color='green'>
          {time}
        </Tag>
      );
    } else if (responseTime <= 3000) {
      return (
        <Tag size='large' color='lime'>
          {time}
        </Tag>
      );
    } else if (responseTime <= 5000) {
      return (
        <Tag size='large' color='yellow'>
          {time}
        </Tag>
      );
    } else {
      return (
        <Tag size='large' color='red'>
          {time}
        </Tag>
      );
    }
  };

  // Define column keys for selection
  const COLUMN_KEYS = {
    ID: 'id',
    NAME: 'name',
    GROUP: 'group',
    TYPE: 'type',
    STATUS: 'status',
    RESPONSE_TIME: 'response_time',
    BALANCE: 'balance',
    PRIORITY: 'priority',
    WEIGHT: 'weight',
    OPERATE: 'operate',
  };

  // State for column visibility
  const [visibleColumns, setVisibleColumns] = useState({});
  const [showColumnSelector, setShowColumnSelector] = useState(false);

  // Load saved column preferences from localStorage
  useEffect(() => {
    const savedColumns = localStorage.getItem('channels-table-columns');
    if (savedColumns) {
      try {
        const parsed = JSON.parse(savedColumns);
        // Make sure all columns are accounted for
        const defaults = getDefaultColumnVisibility();
        const merged = { ...defaults, ...parsed };
        setVisibleColumns(merged);
      } catch (e) {
        console.error('Failed to parse saved column preferences', e);
        initDefaultColumns();
      }
    } else {
      initDefaultColumns();
    }
  }, []);

  // Update table when column visibility changes
  useEffect(() => {
    if (Object.keys(visibleColumns).length > 0) {
      // Save to localStorage
      localStorage.setItem(
        'channels-table-columns',
        JSON.stringify(visibleColumns),
      );
    }
  }, [visibleColumns]);

  // Get default column visibility
  const getDefaultColumnVisibility = () => {
    return {
      [COLUMN_KEYS.ID]: true,
      [COLUMN_KEYS.NAME]: true,
      [COLUMN_KEYS.GROUP]: true,
      [COLUMN_KEYS.TYPE]: true,
      [COLUMN_KEYS.STATUS]: true,
      [COLUMN_KEYS.RESPONSE_TIME]: true,
      [COLUMN_KEYS.BALANCE]: true,
      [COLUMN_KEYS.PRIORITY]: true,
      [COLUMN_KEYS.WEIGHT]: true,
      [COLUMN_KEYS.OPERATE]: true,
    };
  };

  // Initialize default column visibility
  const initDefaultColumns = () => {
    const defaults = getDefaultColumnVisibility();
    setVisibleColumns(defaults);
  };

  // Handle column visibility change
  const handleColumnVisibilityChange = (columnKey, checked) => {
    const updatedColumns = { ...visibleColumns, [columnKey]: checked };
    setVisibleColumns(updatedColumns);
  };

  // Handle "Select All" checkbox
  const handleSelectAll = (checked) => {
    const allKeys = Object.keys(COLUMN_KEYS).map((key) => COLUMN_KEYS[key]);
    const updatedColumns = {};

    allKeys.forEach((key) => {
      updatedColumns[key] = checked;
    });

    setVisibleColumns(updatedColumns);
  };

  // Define all columns with keys
  const allColumns = [
    {
      key: COLUMN_KEYS.ID,
      title: t('ID'),
      dataIndex: 'id',
    },
    {
      key: COLUMN_KEYS.NAME,
      title: t('名称'),
      dataIndex: 'name',
    },
    {
      key: COLUMN_KEYS.GROUP,
      title: t('分组'),
      dataIndex: 'group',
      render: (text, record, index) => {
        return (
          <div>
            <Space spacing={2}>
              {text
                ?.split(',')
                .sort((a, b) => {
                  if (a === 'default') return -1;
                  if (b === 'default') return 1;
                  return a.localeCompare(b);
                })
                .map((item, index) => {
                  return renderGroup(item);
                })}
            </Space>
          </div>
        );
      },
    },
    {
      key: COLUMN_KEYS.TYPE,
      title: t('类型'),
      dataIndex: 'type',
      render: (text, record, index) => {
        if (record.children === undefined) {
          return <>{renderType(text)}</>;
        } else {
          return <>{renderTagType()}</>;
        }
      },
    },
    {
      key: COLUMN_KEYS.STATUS,
      title: t('状态'),
      dataIndex: 'status',
      render: (text, record, index) => {
        if (text === 3) {
          if (record.other_info === '') {
            record.other_info = '{}';
          }
          let otherInfo = JSON.parse(record.other_info);
          let reason = otherInfo['status_reason'];
          let time = otherInfo['status_time'];
          return (
            <div>
              <Tooltip
                content={
                  t('原因:') + reason + t(',时间:') + timestamp2string(time)
                }
              >
                {renderStatus(text)}
              </Tooltip>
            </div>
          );
        } else {
          return renderStatus(text);
        }
      },
    },
    {
      key: COLUMN_KEYS.RESPONSE_TIME,
      title: t('响应时间'),
      dataIndex: 'response_time',
      render: (text, record, index) => {
        return <div>{renderResponseTime(text)}</div>;
      },
    },
    {
      key: COLUMN_KEYS.BALANCE,
      title: t('已用/剩余'),
      dataIndex: 'expired_time',
      render: (text, record, index) => {
        if (record.children === undefined) {
          return (
            <div>
              <Space spacing={1}>
                <Tooltip content={t('已用额度')}>
                  <Tag color='white' type='ghost' size='large'>
                    {renderQuota(record.used_quota)}
                  </Tag>
                </Tooltip>
                <Tooltip
                  content={t('剩余额度') + record.balance + t(',点击更新')}
                >
                  <Tag
                    color='white'
                    type='ghost'
                    size='large'
                    onClick={() => {
                      updateChannelBalance(record);
                    }}
                  >
                    ${renderNumberWithPoint(record.balance)}
                  </Tag>
                </Tooltip>
              </Space>
            </div>
          );
        } else {
          return (
            <Tooltip content={t('已用额度')}>
              <Tag color='white' type='ghost' size='large'>
                {renderQuota(record.used_quota)}
              </Tag>
            </Tooltip>
          );
        }
      },
    },
    {
      key: COLUMN_KEYS.PRIORITY,
      title: t('优先级'),
      dataIndex: 'priority',
      render: (text, record, index) => {
        if (record.children === undefined) {
          return (
            <div>
              <InputNumber
                style={{ width: 70 }}
                name='priority'
                onBlur={(e) => {
                  manageChannel(record.id, 'priority', record, e.target.value);
                }}
                keepFocus={true}
                innerButtons
                defaultValue={record.priority}
                min={-999}
              />
            </div>
          );
        } else {
          return (
            <>
              <InputNumber
                style={{ width: 70 }}
                name='priority'
                keepFocus={true}
                onBlur={(e) => {
                  Modal.warning({
                    title: t('修改子渠道优先级'),
                    content:
                      t('确定要修改所有子渠道优先级为 ') +
                      e.target.value +
                      t(' 吗?'),
                    onOk: () => {
                      if (e.target.value === '') {
                        return;
                      }
                      submitTagEdit('priority', {
                        tag: record.key,
                        priority: e.target.value,
                      });
                    },
                  });
                }}
                innerButtons
                defaultValue={record.priority}
                min={-999}
              />
            </>
          );
        }
      },
    },
    {
      key: COLUMN_KEYS.WEIGHT,
      title: t('权重'),
      dataIndex: 'weight',
      render: (text, record, index) => {
        if (record.children === undefined) {
          return (
            <div>
              <InputNumber
                style={{ width: 70 }}
                name='weight'
                onBlur={(e) => {
                  manageChannel(record.id, 'weight', record, e.target.value);
                }}
                keepFocus={true}
                innerButtons
                defaultValue={record.weight}
                min={0}
              />
            </div>
          );
        } else {
          return (
            <InputNumber
              style={{ width: 70 }}
              name='weight'
              keepFocus={true}
              onBlur={(e) => {
                Modal.warning({
                  title: t('修改子渠道权重'),
                  content:
                    t('确定要修改所有子渠道权重为 ') +
                    e.target.value +
                    t(' 吗?'),
                  onOk: () => {
                    if (e.target.value === '') {
                      return;
                    }
                    submitTagEdit('weight', {
                      tag: record.key,
                      weight: e.target.value,
                    });
                  },
                });
              }}
              innerButtons
              defaultValue={record.weight}
              min={-999}
            />
          );
        }
      },
    },
    {
      key: COLUMN_KEYS.OPERATE,
      title: '',
      dataIndex: 'operate',
      render: (text, record, index) => {
        if (record.children === undefined) {
          return (
            <div>
              <SplitButtonGroup
                style={{ marginRight: 1 }}
                aria-label={t('测试单个渠道操作项目组')}
              >
                <Button
                  theme='light'
                  onClick={() => {
                    testChannel(record, '');
                  }}
                >
                  {t('测试')}
                </Button>
                <Button
                  style={{ padding: '8px 4px' }}
                  type='primary'
                  icon={<IconTreeTriangleDown />}
                  onClick={() => {
                    setCurrentTestChannel(record);
                    setShowModelTestModal(true);
                  }}
                ></Button>
              </SplitButtonGroup>
              <Popconfirm
                title={t('确定是否要删除此渠道?')}
                content={t('此修改将不可逆')}
                okType={'danger'}
                position={'left'}
                onConfirm={() => {
                  manageChannel(record.id, 'delete', record).then(() => {
                    removeRecord(record);
                  });
                }}
              >
                <Button theme='light' type='danger' style={{ marginRight: 1 }}>
                  {t('删除')}
                </Button>
              </Popconfirm>
              {record.status === 1 ? (
                <Button
                  theme='light'
                  type='warning'
                  style={{ marginRight: 1 }}
                  onClick={async () => {
                    manageChannel(record.id, 'disable', record);
                  }}
                >
                  {t('禁用')}
                </Button>
              ) : (
                <Button
                  theme='light'
                  type='secondary'
                  style={{ marginRight: 1 }}
                  onClick={async () => {
                    manageChannel(record.id, 'enable', record);
                  }}
                >
                  {t('启用')}
                </Button>
              )}
              <Button
                theme='light'
                type='tertiary'
                style={{ marginRight: 1 }}
                onClick={() => {
                  setEditingChannel(record);
                  setShowEdit(true);
                }}
              >
                {t('编辑')}
              </Button>
              <Popconfirm
                title={t('确定是否要复制此渠道?')}
                content={t('复制渠道的所有信息')}
                okType={'danger'}
                position={'left'}
                onConfirm={async () => {
                  copySelectedChannel(record);
                }}
              >
                <Button theme='light' type='primary' style={{ marginRight: 1 }}>
                  {t('复制')}
                </Button>
              </Popconfirm>
            </div>
          );
        } else {
          return (
            <>
              <Button
                theme='light'
                type='secondary'
                style={{ marginRight: 1 }}
                onClick={async () => {
                  manageTag(record.key, 'enable');
                }}
              >
                {t('启用全部')}
              </Button>
              <Button
                theme='light'
                type='warning'
                style={{ marginRight: 1 }}
                onClick={async () => {
                  manageTag(record.key, 'disable');
                }}
              >
                {t('禁用全部')}
              </Button>
              <Button
                theme='light'
                type='tertiary'
                style={{ marginRight: 1 }}
                onClick={() => {
                  setShowEditTag(true);
                  setEditingTag(record.key);
                }}
              >
                {t('编辑')}
              </Button>
            </>
          );
        }
      },
    },
  ];

  // Filter columns based on visibility settings
  const getVisibleColumns = () => {
    return allColumns.filter((column) => visibleColumns[column.key]);
  };

  // Column selector modal
  const renderColumnSelector = () => {
    return (
      <Modal
        title={t('列设置')}
        visible={showColumnSelector}
        onCancel={() => setShowColumnSelector(false)}
        footer={
          <>
            <Button onClick={() => initDefaultColumns()}>{t('重置')}</Button>
            <Button onClick={() => setShowColumnSelector(false)}>
              {t('取消')}
            </Button>
            <Button type='primary' onClick={() => setShowColumnSelector(false)}>
              {t('确定')}
            </Button>
          </>
        }
        style={{ width: isMobile() ? '90%' : 500 }}
        bodyStyle={{ padding: '24px' }}
      >
        <div style={{ marginBottom: 20 }}>
          <Checkbox
            checked={Object.values(visibleColumns).every((v) => v === true)}
            indeterminate={
              Object.values(visibleColumns).some((v) => v === true) &&
              !Object.values(visibleColumns).every((v) => v === true)
            }
            onChange={(e) => handleSelectAll(e.target.checked)}
          >
            {t('全选')}
          </Checkbox>
        </div>
        <div
          style={{
            display: 'flex',
            flexWrap: 'wrap',
            maxHeight: '400px',
            overflowY: 'auto',
            border: '1px solid var(--semi-color-border)',
            borderRadius: '6px',
            padding: '16px',
          }}
        >
          {allColumns.map((column) => {
            // Skip columns without title
            if (!column.title) {
              return null;
            }

            return (
              <div
                key={column.key}
                style={{
                  width: isMobile() ? '100%' : '50%',
                  marginBottom: 16,
                  paddingRight: 8,
                }}
              >
                <Checkbox
                  checked={!!visibleColumns[column.key]}
                  onChange={(e) =>
                    handleColumnVisibilityChange(column.key, e.target.checked)
                  }
                >
                  {column.title}
                </Checkbox>
              </div>
            );
          })}
        </div>
      </Modal>
    );
  };

  const [channels, setChannels] = useState([]);
  const [loading, setLoading] = useState(true);
  const [activePage, setActivePage] = useState(1);
  const [idSort, setIdSort] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [searchGroup, setSearchGroup] = useState('');
  const [searchModel, setSearchModel] = useState('');
  const [searching, setSearching] = useState(false);
  const [selectedTypes, setSelectedTypes] = useState([]); // 新增:类型多选
  const [selectedStatuses, setSelectedStatuses] = useState([]); // 新增:状态多选
  const [selectedTags, setSelectedTags] = useState([]); // 新增:标签多选
  const [tagOptions, setTagOptions] = useState([]); // 新增:标签选项

  const [updatingBalance, setUpdatingBalance] = useState(false);
  const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
  const [showPrompt, setShowPrompt] = useState(
    shouldShowPrompt('channel-test'),
  );
  const [channelCount, setChannelCount] = useState(pageSize);
  const [groupOptions, setGroupOptions] = useState([]);
  const [showEdit, setShowEdit] = useState(false);
  const [enableBatchDelete, setEnableBatchDelete] = useState(false);
  const [editingChannel, setEditingChannel] = useState({
    id: undefined,
  });
  const [showEditTag, setShowEditTag] = useState(false);
  const [editingTag, setEditingTag] = useState('');
  const [selectedChannels, setSelectedChannels] = useState([]);
  const [showEditPriority, setShowEditPriority] = useState(false);
  const [enableTagMode, setEnableTagMode] = useState(() => {
    const savedState = localStorage.getItem('channel-tag-mode');
    return savedState !== null ? JSON.parse(savedState) : false;
  });
  useEffect(() => {
    localStorage.setItem('channel-tag-mode', JSON.stringify(enableTagMode));
  }, [enableTagMode]);
  const [showBatchSetTag, setShowBatchSetTag] = useState(false);
  const [batchSetTagValue, setBatchSetTagValue] = useState('');
  const [showModelTestModal, setShowModelTestModal] = useState(false);
  const [currentTestChannel, setCurrentTestChannel] = useState(null);
  const [modelSearchKeyword, setModelSearchKeyword] = useState('');
  // 测试结果缓存
  const [testResultsCache, setTestResultsCache] = useState(() => Object.create(null));
  // 批量测试相关状态
  const [isBatchTesting, setIsBatchTesting] = useState(false);
  const [batchTestResults, setBatchTestResults] = useState([]);
  const [currentTestingModel, setCurrentTestingModel] = useState('');
  const [testProgress, setTestProgress] = useState({ completed: 0, total: 0 });
  const [concurrentLimit, setConcurrentLimit] = useState(3); // 默认并发数
  const [batchTestDelay, setBatchTestDelay] = useState(200); // 批次间延迟(ms)
  // 批量测试控制
  const [batchTestAbortController, setBatchTestAbortController] = useState(null);

  const removeRecord = (record) => {
    let newDataSource = [...channels];
    if (record.id != null) {
      let idx = newDataSource.findIndex((data) => {
        if (data.children !== undefined) {
          for (let i = 0; i < data.children.length; i++) {
            if (data.children[i].id === record.id) {
              data.children.splice(i, 1);
              return false;
            }
          }
        } else {
          return data.id === record.id;
        }
      });

      if (idx > -1) {
        newDataSource.splice(idx, 1);
        setChannels(newDataSource);
      }
    }
  };

  const setChannelFormat = (channels, enableTagMode) => {
    let channelDates = [];
    let channelTags = {};
    for (let i = 0; i < channels.length; i++) {
      // 为React Table设置key属性,同时保留原始的key字段(API密钥)
      channels[i].rowKey = '' + channels[i].id;
      if (!enableTagMode) {
        channelDates.push(channels[i]);
      } else {
        let tag = channels[i].tag ? channels[i].tag : '';
        // find from channelTags
        let tagIndex = channelTags[tag];
        let tagChannelDates = undefined;
        if (tagIndex === undefined) {
          // not found, create a new tag
          channelTags[tag] = 1;
          tagChannelDates = {
            rowKey: tag,  // React Table的key
            key: tag,     // 标签名
            id: tag,
            tag: tag,
            name: '标签:' + tag,
            group: '',
            used_quota: 0,
            response_time: 0,
            priority: -1,
            weight: -1,
          };
          tagChannelDates.children = [];
          channelDates.push(tagChannelDates);
        } else {
          // found, add to the tag
          tagChannelDates = channelDates.find((item) => item.key === tag);
        }
        if (tagChannelDates.priority === -1) {
          tagChannelDates.priority = channels[i].priority;
        } else {
          if (tagChannelDates.priority !== channels[i].priority) {
            tagChannelDates.priority = '';
          }
        }
        if (tagChannelDates.weight === -1) {
          tagChannelDates.weight = channels[i].weight;
        } else {
          if (tagChannelDates.weight !== channels[i].weight) {
            tagChannelDates.weight = '';
          }
        }

        if (tagChannelDates.group === '') {
          tagChannelDates.group = channels[i].group;
        } else {
          let channelGroupsStr = channels[i].group;
          channelGroupsStr.split(',').forEach((item, index) => {
            if (tagChannelDates.group.indexOf(item) === -1) {
              // join
              tagChannelDates.group += ',' + item;
            }
          });
        }

        tagChannelDates.children.push(channels[i]);
        if (channels[i].status === 1) {
          tagChannelDates.status = 1;
        }
        tagChannelDates.used_quota += channels[i].used_quota;
        tagChannelDates.response_time += channels[i].response_time;
        tagChannelDates.response_time = tagChannelDates.response_time / 2;
      }
    }
    // 为React Table设置rowKey属性
    setChannels(channelDates);
    if (channelDates.length >= pageSize) {
      setChannelCount(channelDates.length + pageSize);
    } else {
      setChannelCount(channelDates.length);
    }
  };

  const loadChannels = async (startIdx, pageSize, idSort, enableTagMode) => {
    setLoading(true);
    const res = await API.get(
      `/api/channel/?p=${startIdx}&page_size=${pageSize}&id_sort=${idSort}&tag_mode=${enableTagMode}`,
    );
    if (res === undefined) {
      return;
    }
    const { success, message, data } = res.data;
    if (success) {
      if (startIdx === 0) {
        setChannelFormat(data, enableTagMode);
      } else {
        let newChannels = [...channels];
        newChannels.splice(startIdx * pageSize, data.length, ...data);
        setChannelFormat(newChannels, enableTagMode);
      }
    } else {
      showError(message);
    }
    setLoading(false);
  };

  const copySelectedChannel = async (record) => {
    const channelToCopy = record;
    channelToCopy.name += t('_复制');
    channelToCopy.created_time = null;
    channelToCopy.balance = 0;
    channelToCopy.used_quota = 0;
    if (!channelToCopy) {
      showError(t('渠道未找到,请刷新页面后重试。'));
      return;
    }
    try {
      const newChannel = { ...channelToCopy, id: undefined };
      const response = await API.post('/api/channel/', newChannel);
      if (response.data.success) {
        showSuccess(t('渠道复制成功'));
        await refresh();
      } else {
        showError(response.data.message);
      }
    } catch (error) {
      showError(t('渠道复制失败: ') + error.message);
    }
  };

   const refresh = async () => {
    if (searchKeyword === '' && searchGroup === '' && searchModel === '') {
      await loadChannels(activePage - 1, pageSize, idSort, enableTagMode);
    } else {
      await searchChannels(
        searchKeyword,
        searchGroup,
        searchModel,
        enableTagMode,
      );
    }
  };

   useEffect(() => {
    // console.log('default effect')
    const localIdSort = localStorage.getItem('id-sort') === 'true';
    const localPageSize =
      parseInt(localStorage.getItem('page-size')) || ITEMS_PER_PAGE;
    setIdSort(localIdSort);
    setPageSize(localPageSize);
    loadChannels(0, localPageSize, localIdSort, enableTagMode)
      .then()
      .catch((reason) => {
        showError(reason);
      });
    fetchGroups().then();
    loadChannelModels().then();
    // 加载测试结果缓存
    loadTestResultsCache();
  }, []);

  // 监听模态框可见性变化,加载缓存的测试结果
  useEffect(() => {
    if (showModelTestModal && currentTestChannel) {
      const cachedResults = getCachedTestResults(currentTestChannel.id);
      if (cachedResults) {
        setBatchTestResults(cachedResults);
        setTestProgress({ 
          completed: cachedResults.length, 
          total: currentTestChannel.models?.split(',').filter(m => m.trim()).length || 0 
        });
      }
    }
  }, [showModelTestModal, currentTestChannel]);

  // 加载测试结果缓存
  const loadTestResultsCache = () => {
    try {
      const cached = localStorage.getItem('channel-test-results-cache');
      if (cached) {
        const parsedCache = JSON.parse(cached);
        // 清理过期的缓存(超过24小时)
        const now = Date.now();
        const validCache = Object.create(null);
        
        Object.keys(parsedCache).forEach(channelId => {
          // 验证channelId是安全的字符串,防止原型污染
          if (channelId === '__proto__' || 
              channelId === 'constructor' || 
              channelId === 'prototype') {
            return;
          }
          
          const channelCache = parsedCache[channelId];
          // 验证channelCache是对象且timestamp是有限数字
          if (channelCache && 
              typeof channelCache === 'object' &&
              channelCache !== null &&
              typeof channelCache.timestamp === 'number' &&
              Number.isFinite(channelCache.timestamp) &&
              (now - channelCache.timestamp) < 24 * 60 * 60 * 1000) {
            validCache[channelId] = channelCache;
          }
        });
        
        setTestResultsCache(validCache);
        // 更新localStorage中的有效缓存
        if (Object.keys(validCache).length !== Object.keys(parsedCache).length) {
          localStorage.setItem('channel-test-results-cache', JSON.stringify(validCache));
        }
      }
    } catch (e) {
      console.error('加载测试结果缓存失败:', e);
      localStorage.removeItem('channel-test-results-cache');
    }
  };

  // 保存测试结果缓存
  const saveTestResultsCache = (channelId, results) => {
    try {
      // 将channelId转换为字符串并验证安全性,防止原型污染
      const id = String(channelId);
      if (id === '__proto__' || 
          id === 'constructor' || 
          id === 'prototype') {
        console.warn('无效的channelId,跳过缓存保存:', channelId);
        return;
      }
      
      const newCache = Object.assign(Object.create(null), testResultsCache, {
        [id]: {
          results: results,
          timestamp: Date.now()
        }
      });
      setTestResultsCache(newCache);
      localStorage.setItem('channel-test-results-cache', JSON.stringify(newCache));
    } catch (e) {
      console.error('保存测试结果缓存失败:', e);
    }
  };

  // 获取缓存的测试结果
  const getCachedTestResults = (channelId) => {
    // 将channelId转换为字符串并验证安全性,防止原型污染
    const id = String(channelId);
    if (id === '__proto__' || 
        id === 'constructor' || 
        id === 'prototype') {
      return null;
    }
    
    const channelCache = testResultsCache[id];
    if (channelCache && (Date.now() - channelCache.timestamp) < 24 * 60 * 60 * 1000) {
      return channelCache.results;
    }
    return null;
  };

  const manageChannel = async (id, action, record, value) => {
    let data = { id };
    let res;
    switch (action) {
      case 'delete':
        res = await API.delete(`/api/channel/${id}/`);
        break;
      case 'enable':
        data.status = 1;
        res = await API.put('/api/channel/', data);
        break;
      case 'disable':
        data.status = 2;
        res = await API.put('/api/channel/', data);
        break;
      case 'priority':
        if (value === '') {
          return;
        }
        data.priority = parseInt(value);
        res = await API.put('/api/channel/', data);
        break;
      case 'weight':
        if (value === '') {
          return;
        }
        data.weight = parseInt(value);
        if (data.weight < 0) {
          data.weight = 0;
        }
        res = await API.put('/api/channel/', data);
        break;
    }
    const { success, message } = res.data;
    if (success) {
      showSuccess(t('操作成功完成!'));
      let channel = res.data.data;
      let newChannels = [...channels];
      if (action === 'delete') {
      } else {
        record.status = channel.status;
      }
      setChannels(newChannels);
    } else {
      showError(message);
    }
  };

  const manageTag = async (tag, action) => {
    console.log(tag, action);
    let res;
    switch (action) {
      case 'enable':
        res = await API.post('/api/channel/tag/enabled', {
          tag: tag,
        });
        break;
      case 'disable':
        res = await API.post('/api/channel/tag/disabled', {
          tag: tag,
        });
        break;
    }
    const { success, message } = res.data;
    if (success) {
      showSuccess('操作成功完成!');
      let newChannels = [...channels];
      for (let i = 0; i < newChannels.length; i++) {
        if (newChannels[i].tag === tag) {
          let status = action === 'enable' ? 1 : 2;
          newChannels[i]?.children?.forEach((channel) => {
            channel.status = status;
          });
          newChannels[i].status = status;
        }
      }
      setChannels(newChannels);
    } else {
      showError(message);
    }
  };

  // 支持传入覆盖的类型/状态/标签参数,避免因setState异步导致筛选失效
  const searchChannels = async (
    searchKeyword,
    searchGroup,
    searchModel,
    enableTagMode,
    typesOverride = null,
    statusesOverride = null,
    tagsOverride = null,
  ) => {
    const nextTypes = typesOverride !== null ? typesOverride : selectedTypes;
    const nextStatuses = statusesOverride !== null ? statusesOverride : selectedStatuses;
    const nextTags = tagsOverride !== null ? tagsOverride : selectedTags;

    const noBasic = searchKeyword === '' && searchGroup === '' && searchModel === '';
    const noAdvanced = (!nextTypes || nextTypes.length === 0) && (!nextStatuses || nextStatuses.length === 0) && (!nextTags || nextTags.length === 0);
    if (noBasic && noAdvanced) {
      await loadChannels(activePage - 1, pageSize, idSort, enableTagMode);
      return;
    }
    setSearching(true);
    const params = new URLSearchParams();
    
    // 添加基础搜索参数
    params.append('keyword', searchKeyword);
    params.append('group', searchGroup);
    params.append('model', searchModel);
    params.append('id_sort', String(idSort));
    params.append('tag_mode', String(enableTagMode));
    
    // 条件添加数组参数
    if (nextTypes && nextTypes.length > 0) {
      params.append('types', nextTypes.map(Number).join(','));
    }
    if (nextStatuses && nextStatuses.length > 0) {
      params.append('statuses', nextStatuses.map(Number).join(','));
    }
    if (nextTags && nextTags.length > 0) {
      params.append('tags', nextTags.join(','));
    }
    
    const res = await API.get(`/api/channel/search?${params.toString()}`);
    const { success, message, data } = res.data;
    if (success) {
      setChannelFormat(data, enableTagMode);
      setActivePage(1);
    } else {
      showError(message);
    }
    setSearching(false);
  };

  const updateChannelProperty = (channelId, updateFn) => {
    // Create a new copy of channels array
    const newChannels = [...channels];
    let updated = false;

    // Find and update the correct channel
    newChannels.forEach((channel) => {
      if (channel.children !== undefined) {
        // If this is a tag group, search in its children
        channel.children.forEach((child) => {
          if (child.id === channelId) {
            updateFn(child);
            updated = true;
          }
        });
      } else if (channel.id === channelId) {
        // Direct channel match
        updateFn(channel);
        updated = true;
      }
    });

    // Only update state if we actually modified a channel
    if (updated) {
      setChannels(newChannels);
    }
  };

  // 辅助函数:更新测试结果到状态
  const updateTestResult = (model, result) => {
    setBatchTestResults(prevResults => {
      const existingIndex = prevResults.findIndex(r => r.model === model);
      if (existingIndex >= 0) {
        const newResults = [...prevResults];
        newResults[existingIndex] = result;
        return newResults;
      } else {
        return [...prevResults, result];
      }
    });
  };

  // 辅助函数:创建测试结果对象
  const createTestResult = (model, success, message, time = null, isRetryable = true) => ({
    model,
    success,
    message,
    time,
    retryCount: 0,
    isRetryable: success ? false : isRetryable
  });

  // 辅助函数:处理测试成功
  const handleTestSuccess = (record, model, time) => {
    // 更新渠道属性
    updateChannelProperty(record.id, (channel) => {
      channel.response_time = time * 1000;
      channel.test_time = Date.now() / 1000;
    });

    // 更新模态框中的测试结果
    if (shouldUpdateModalResults(record.id)) {
      const result = createTestResult(
        model, 
        true, 
        t('测试成功,耗时 {{time}} 秒', { time: time.toFixed(2) }), 
        time
      );
      updateTestResult(model, result);
    }

    showInfo(
      t('通道 {{name}} 测试成功,耗时 {{time}} 秒。', {
        name: record.name,
        time: time.toFixed(2)
      })
    );
  };

  // 辅助函数:处理测试失败
  const handleTestFailure = (record, model, message) => {
    if (shouldUpdateModalResults(record.id)) {
      const result = createTestResult(model, false, message);
      updateTestResult(model, result);
    }
    showError(message);
  };

  // 辅助函数:判断是否需要更新模态框结果
  const shouldUpdateModalResults = (recordId) => {
    return showModelTestModal && currentTestChannel && currentTestChannel.id === recordId;
  };

  // 主要的测试渠道函数
  const testChannel = async (record, model) => {
    try {
      const res = await API.get(`/api/channel/test/${record.id}?model=${model}`);
      const { success, message, time } = res.data;
      
      if (success) {
        handleTestSuccess(record, model, time);
      } else {
        handleTestFailure(record, model, message);
      }
    } catch (error) {
      handleTestFailure(record, model, error.message || t('测试请求失败'));
    }
  };

  // 统一的取消检测函数
  const isCancellationError = (error) => {
    return (
      error.name === 'AbortError' ||
      error.name === 'CanceledError' ||
      axios.isCancel(error) ||
      error.code === 'ERR_CANCELED'
    );
  };

  // 单个模型测试函数(用于并发)- 支持重试
  const testSingleModel = async (model, abortController, maxRetries = 2) => {
    let lastError = null;
    
    for (let retryCount = 0; retryCount <= maxRetries; retryCount++) {
      try {
        const res = await API.get(`/api/channel/test/${currentTestChannel.id}?model=${encodeURIComponent(model)}`, {
          signal: abortController?.signal
        });
        const { success, message, time } = res.data;

        const result = {
          model,
          success,
          message: success ? `测试成功,耗时 ${time.toFixed(2)} 秒` : message,
          time: success ? time : null,
          retryCount,
          isRetryable: !success && retryCount < maxRetries
        };

        if (success) {
          // 更新渠道状态
          updateChannelProperty(currentTestChannel.id, (channel) => {
            channel.response_time = time * 1000;
            channel.test_time = Date.now() / 1000;
          });
        }

        return result;
      } catch (error) {
        lastError = error;
        
        // 如果是取消请求,立即抛出错误以停止执行
        if (isCancellationError(error) || abortController?.signal?.aborted) {
          throw error;
        }

        // 如果达到最大重试次数,返回失败结果
        if (retryCount >= maxRetries) {
          return {
            model,
            success: false,
            message: error.message || '测试失败',
            time: null,
            retryCount,
            isRetryable: true, // 仍然可以手动重试
            error: error
          };
        }

        // 重试前等待一段时间(指数退避)
        const delay = Math.min(1000 * Math.pow(2, retryCount), 5000);
        await new Promise(resolve => setTimeout(resolve, delay));
      }
    }
  };

  // 分批并发处理函数
  const processBatch = async (models, batchSize, abortController) => {
    const results = [];

    for (let i = 0; i < models.length; i += batchSize) {
      // 4) 每次迭代都检查取消状态
      if (abortController?.signal?.aborted) {
        throw new Error('测试被用户取消');
      }

      const batch = models.slice(i, i + batchSize);
      setCurrentTestingModel(`批次 ${Math.floor(i / batchSize) + 1}: ${batch.join(', ')}`);

      // 4) 在await之前再次检查取消状态
      if (abortController?.signal?.aborted) {
        throw new Error('测试被用户取消');
      }

      // 并发执行当前批次
      const batchPromises = batch.map(model => testSingleModel(model, abortController));
      const batchResults = await Promise.allSettled(batchPromises);

      // 4) 在await之后检查取消状态
      if (abortController?.signal?.aborted) {
        throw new Error('测试被用户取消');
      }

      // 处理批次结果
      const processedResults = batchResults.map((result, index) => {
        if (result.status === 'fulfilled') {
          return result.value;
        } else {
          // 如果是取消错误,直接抛出
          if (isCancellationError(result.reason) || abortController?.signal?.aborted) {
            throw result.reason;
          }
          return {
            model: batch[index],
            success: false,
            message: result.reason?.message || '测试失败',
            time: null
          };
        }
      });

      results.push(...processedResults);

      // 更新进度和结果
      setTestProgress({ completed: results.length, total: models.length });
      setBatchTestResults([...results]);

      // 3) 批次间使用可配置的延迟
      if (i + batchSize < models.length) {
        // 4) 在延迟期间也要检查取消状态
        if (abortController?.signal?.aborted) {
          throw new Error('测试被用户取消');
        }
        await new Promise(resolve => setTimeout(resolve, batchTestDelay));
      }
    }

    return results;
  };

  // 重试失败的模型
  const retryFailedModels = async () => {
    if (!currentTestChannel || isBatchTesting) {
      return;
    }

    const failedModels = batchTestResults.filter(r => !r.success && r.isRetryable);
    if (failedModels.length === 0) {
      showInfo(t('没有可重试的失败模型'));
      return;
    }

    const controller = new AbortController();
    setBatchTestAbortController(controller);
    setIsBatchTesting(true);
    setCurrentTestingModel('重试失败模型...');

    try {
      const failedModelNames = failedModels.map(r => r.model);
      const retryResults = await processBatch(failedModelNames, concurrentLimit, controller);
      
      // 更新批量测试结果,合并重试结果
      const updatedResults = batchTestResults.map(result => {
        const retryResult = retryResults.find(r => r.model === result.model);
        return retryResult || result;
      });
      
      setBatchTestResults(updatedResults);
      
      const newSuccessCount = retryResults.filter(r => r.success).length;
      showInfo(t('重试完成:成功 {{successCount}} 个,失败 {{failCount}} 个', { 
        successCount: newSuccessCount, 
        failCount: failedModelNames.length - newSuccessCount 
      }));
    } catch (error) {
      if (isCancellationError(error)) {
        showInfo(t('重试已取消'));
      } else {
        showError(t('重试过程中发生错误:') + error.message);
      }
    } finally {
      setIsBatchTesting(false);
      setCurrentTestingModel('');
      setBatchTestAbortController(null);
    }
  };

  // 处理模型测试弹窗关闭
  const handleModelTestModalClose = () => {
    // 停止正在进行的批量测试
    if (batchTestAbortController) {
      batchTestAbortController.abort();
      setBatchTestAbortController(null);
    }
    setShowModelTestModal(false);
    setModelSearchKeyword('');
    // 重置批量测试相关状态
    setIsBatchTesting(false);
    setBatchTestResults([]);
    setCurrentTestingModel('');
    setTestProgress({ completed: 0, total: 0 });
  };

  // 处理删除失败模型
  const handleDeleteFailedModels = (failedModels) => {
    const currentModels = currentTestChannel.models.split(',').map(m => m.trim());
    const failedModelNames = failedModels.map(r => r.model);
    // 优化性能:将数组转换为 Set,查找时间复杂度从 O(M) 降低到 O(1)
    const failedModelNamesSet = new Set(failedModelNames);
    const remainingModels = currentModels.filter(m => !failedModelNamesSet.has(m));
    
    if (remainingModels.length === 0) {
      Modal.warning({
        title: t('无法删除所有模型'),
        content: t('删除这些失败的模型会导致渠道没有任何可用模型,这将使渠道无法正常工作。请至少保留一个模型或先添加新的可用模型。'),
      });
      return;
    }
    
    Modal.confirm({
      title: t('批量删除失败模型'),
      content: (
        <div>
          <p>{t('确定要删除所有 {{count}} 个测试失败的模型吗?此操作不可撤销。', { count: failedModels.length })}</p>
          <p style={{ color: '#52c41a', marginTop: '8px' }}>
            {t('删除后将保留 {{remaining}} 个正常模型:', { remaining: remainingModels.length })}
          </p>
          <div style={{ 
            maxHeight: '100px', 
            overflowY: 'auto', 
            background: 'var(--semi-color-fill-0)', 
            padding: '8px', 
            borderRadius: '4px',
            marginTop: '4px'
          }}>
            {remainingModels.map((model, index) => (
              <div key={index} style={{ fontSize: '12px' }}>{model}</div>
            ))}
          </div>
        </div>
      ),
      onOk: async () => {
        try {
          const newModels = remainingModels;

          const updateData = {
            id: currentTestChannel.id,
            models: newModels.join(','),
          };

          const res = await API.put('/api/channel/', updateData);
          if (res.data.success) {
            updateChannelProperty(currentTestChannel.id, (channel) => {
              channel.models = newModels.join(',');
            });
            setCurrentTestChannel({
              ...currentTestChannel,
              models: newModels.join(',')
            });

            setBatchTestResults(prev => prev.filter(r => !failedModelNamesSet.has(r.model)));
            await refresh();
            showSuccess(t('已删除 {{count}} 个失败的模型', { count: failedModels.length }));
          } else {
            showError(res.data.message || t('批量删除失败'));
          }
        } catch (error) {
          showError(error.message || t('批量删除失败'));
        }
      }
    });
  };

  // 批量测试所有模型(并发版本)
  const testAllModels = async () => {
    // 1) 验证currentTestChannel存在且具有期望的属性
    if (!currentTestChannel || 
        typeof currentTestChannel !== 'object' ||
        !currentTestChannel.id ||
        !currentTestChannel.models ||
        typeof currentTestChannel.models !== 'string') {
      showError(t('当前测试渠道无效或缺少必需属性'));
      return;
    }

    // 修剪空白、去重并过滤空字符串
    const models = [...new Set(
      currentTestChannel.models
        .split(',')
        .map(model => model.trim())
        .filter(model => model.length > 0)
    )];
    if (models.length === 0) {
      showError(t('没有可测试的模型'));
      return;
    }

    // 创建 AbortController
    const controller = new AbortController();
    setBatchTestAbortController(controller);

    setIsBatchTesting(true);
    setBatchTestResults([]);
    setCurrentTestingModel('');
    setTestProgress({ completed: 0, total: models.length });

    // 2) 使用try-catch-finally包装整个异步测试逻辑
    try {
      const results = await processBatch(models, concurrentLimit, controller);

      const successCount = results.filter(r => r.success).length;
      const failCount = results.filter(r => !r.success).length;

      // 保存测试结果到缓存
      saveTestResultsCache(currentTestChannel.id, results);

      showInfo(t('批量测试完成:成功 {{successCount}} 个,失败 {{failCount}} 个', { 
        successCount, 
        failCount 
      }));
    } catch (error) {
      if (isCancellationError(error) || error.message.includes('取消')) {
        showInfo(t('测试已取消'));
      } else {
        showError(t('批量测试过程中发生错误:') + error.message);
      }
    } finally {
      // 3) 确保在finally中重置状态
      setIsBatchTesting(false);
      setCurrentTestingModel('');
      setBatchTestAbortController(null);
    }
  };

  const updateChannelBalance = async (record) => {
    const res = await API.get(`/api/channel/update_balance/${record.id}/`);
    const { success, message, balance } = res.data;
    if (success) {
      updateChannelProperty(record.id, (channel) => {
        channel.balance = balance;
        channel.balance_updated_time = Date.now() / 1000;
      });
      showInfo(
        t('通道 {{name}} 余额更新成功!', { name: record.name }),
      );
    } else {
      showError(message);
    }
  };

  const testAllChannels = async () => {
    const res = await API.get(`/api/channel/test`);
    const { success, message } = res.data;
    if (success) {
      showInfo(t('已成功开始测试所有已启用通道,请刷新页面查看结果。'));
    } else {
      showError(message);
    }
  };

  const deleteAllDisabledChannels = async () => {
    const res = await API.delete(`/api/channel/disabled`);
    const { success, message, data } = res.data;
    if (success) {
      showSuccess(
        t('已删除所有禁用渠道,共计 {{count}} 个', { count: data }),
      );
      await refresh();
    } else {
      showError(message);
    }
  };

  const updateAllChannelsBalance = async () => {
    setUpdatingBalance(true);
    const res = await API.get(`/api/channel/update_balance`);
    const { success, message } = res.data;
    if (success) {
      showInfo(t('已更新完毕所有已启用通道余额!'));
    } else {
      showError(message);
    }
    setUpdatingBalance(false);
  };

  const batchDeleteChannels = async () => {
    if (selectedChannels.length === 0) {
      showError(t('请先选择要删除的通道!'));
      return;
    }
    setLoading(true);
    let ids = [];
    selectedChannels.forEach((channel) => {
      ids.push(channel.id);
    });
    const res = await API.post(`/api/channel/batch`, { ids: ids });
    const { success, message, data } = res.data;
    if (success) {
      showSuccess(t('已删除 {{count}} 个通道!', { count: data }));
      await refresh();
    } else {
      showError(message);
    }
    setLoading(false);
  };

  const fixChannelsAbilities = async () => {
    const res = await API.post(`/api/channel/fix`);
    const { success, message, data } = res.data;
    if (success) {
      showSuccess(t('已修复 {{count}} 个通道!', { count: data }));
      await refresh();
    } else {
      showError(message);
    }
  };

  let pageData = channels.slice(
    (activePage - 1) * pageSize,
    activePage * pageSize,
  );

  const handlePageChange = (page) => {
    setActivePage(page);
    if (page === Math.ceil(channels.length / pageSize) + 1) {
      // In this case we have to load more data and then append them.
      loadChannels(page - 1, pageSize, idSort, enableTagMode).then((r) => {});
    }
  };

  const handlePageSizeChange = async (size) => {
    localStorage.setItem('page-size', size + '');
    setPageSize(size);
    setActivePage(1);
    loadChannels(0, size, idSort, enableTagMode)
      .then()
      .catch((reason) => {
        showError(reason);
      });
  };

  const fetchGroups = async () => {
    try {
      let res = await API.get(`/api/group/`);
      // add 'all' option
      // res.data.data.unshift('all');
      if (res === undefined) {
        return;
      }
      setGroupOptions(
        res.data.data.map((group) => ({
          label: group,
          value: group,
        })),
      );
    } catch (error) {
      showError(error.message);
    }
  };

  const submitTagEdit = async (type, data) => {
    switch (type) {
      case 'priority':
        if (data.priority === undefined || data.priority === '') {
            showError(t('优先级必须是整数!'));
          return;
        }
        data.priority = parseInt(data.priority);
        break;
      case 'weight':
        if (
          data.weight === undefined ||
          data.weight < 0 ||
          data.weight === ''
        ) {
          showInfo(t('权重必须是非负整数!'));
          return;
        }
        data.weight = parseInt(data.weight);
        break;
    }

    try {
      const res = await API.put('/api/channel/tag', data);
      if (res?.data?.success) {
        showSuccess(t('更新成功!'));
        await refresh();
      }
    } catch (error) {
      showError(error);
    }
  };

  const closeEdit = () => {
    setShowEdit(false);
  };

  const handleRow = (record, index) => {
    if (record.status !== 1) {
      return {
        style: {
          background: 'var(--semi-color-disabled-border)',
        },
      };
    } else {
      return {};
    }
  };

  const batchSetChannelTag = async () => {
    if (selectedChannels.length === 0) {
      showError(t('请先选择要设置标签的渠道!'));
      return;
    }
    if (batchSetTagValue === '') {
      showError(t('标签不能为空!'));
      return;
    }
    let ids = selectedChannels.map((channel) => channel.id);
    const res = await API.post('/api/channel/batch/tag', {
      ids: ids,
      tag: batchSetTagValue === '' ? null : batchSetTagValue,
    });
    if (res.data.success) {
      showSuccess(
        t('已为 {{count}} 个渠道设置标签!', { count: res.data.data }),
      );
      await refresh();
      setShowBatchSetTag(false);
    } else {
      showError(res.data.message);
    }
  };

  return (
    <>
      {renderColumnSelector()}
      <EditTagModal
        visible={showEditTag}
        tag={editingTag}
        handleClose={() => setShowEditTag(false)}
        refresh={refresh}
      />
      <EditChannel
        refresh={refresh}
        visible={showEdit}
        handleClose={closeEdit}
        editingChannel={editingChannel}
      />
      <Form
        onSubmit={() => {
          searchChannels(
            searchKeyword,
            searchGroup,
            searchModel,
            enableTagMode,
          );
        }}
        labelPosition='left'
      >
        <div style={{ display: 'flex' }}>
          <Space>
            <Form.Input
              field='search_keyword'
              label={t('搜索渠道关键词')}
              placeholder={t('搜索渠道的 ID名称和密钥 ...')}
              value={searchKeyword}
              loading={searching}
              onChange={(v) => {
                setSearchKeyword(v.trim());
              }}
            />
            <Form.Input
              field='search_model'
              label={t('模型')}
              placeholder={t('模型关键字')}
              value={searchModel}
              loading={searching}
              onChange={(v) => {
                setSearchModel(v.trim());
              }}
            />
            <Form.Select
              field='group'
              label={t('分组')}
              optionList={[
                { label: t('选择分组'), value: null },
                ...groupOptions,
              ]}
              onChange={(v) => {
                setSearchGroup(v);
                searchChannels(searchKeyword, v, searchModel, enableTagMode);
              }}
            />
            {/* 新增:类型多选 */}
            <Form.Select
              field='types'
              label={t('渠道类型')}
              multiple
              optionList={CHANNEL_OPTIONS.map(o => ({ label: o.label, value: o.value }))}
              onChange={(v) => {
                const next = (v || []).map(Number);
                setSelectedTypes(next);
                searchChannels(searchKeyword, searchGroup, searchModel, enableTagMode, next, null, null);
              }}
            />
            {/* 新增:状态多选 */}
            <Form.Select
              field='statuses'
              label={t('渠道状态')}
              multiple
              optionList={[{label:t('已启用'), value:1}, {label:t('已禁用'), value:2}, {label:t('自动禁用'), value:3}]}
              onChange={(v) => {
                const next = (v || []).map(Number);
                setSelectedStatuses(next);
                searchChannels(searchKeyword, searchGroup, searchModel, enableTagMode, null, next, null);
              }}
            />
            {/* 新增:标签多选 */}
            <Form.Select
              field='tags'
              label={t('标签')}
              multiple
              optionList={tagOptions}
              filter
              onFocus={async ()=>{
                if (tagOptions.length===0) {
                  const res = await API.get('/api/channel/tags?offset=0&limit=200');
                  const opts = (res?.data?.data||[]).filter(Boolean).map(t=>({label:t, value:t}));
                  setTagOptions(opts);
                }
              }}
              onChange={(v) => {
                const next = (v || []);
                setSelectedTags(next);
                searchChannels(searchKeyword, searchGroup, searchModel, enableTagMode, null, null, next);
              }}
            />
            <Button
              theme='light'
              type='tertiary'
              onClick={() => {
                setSearchKeyword('');
                setSearchGroup('');
                setSearchModel('');
                setSelectedTypes([]);
                setSelectedStatuses([]);
                setSelectedTags([]);
                loadChannels(0, pageSize, idSort, enableTagMode);
              }}
            >{t('重置条件')}</Button>


            <Button
              label={t('查询')}
              type='primary'
              htmlType='submit'
              className='btn-margin-right'
              style={{ marginRight: 8 }}
            >
              {t('查询')}
            </Button>
          </Space>
        </div>
      </Form>
      <Divider style={{ marginBottom: 15 }} />
      <div
        style={{
          display: 'flex',
          flexDirection: isMobile() ? 'column' : 'row',
          marginTop: isMobile() ? 0 : -45,
          zIndex: 999,
          pointerEvents: 'none',
        }}
      >
        <Space
          style={{
            pointerEvents: 'auto',
            marginTop: isMobile() ? 0 : 45,
            marginBottom: isMobile() ? 16 : 0,
            display: 'flex',
            flexWrap: isMobile() ? 'wrap' : 'nowrap',
            gap: '8px',
          }}
        >
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              marginRight: 16,
              flexWrap: 'nowrap',
            }}
          >
            <Typography.Text strong style={{ marginRight: 8 }}>
              {t('使用ID排序')}
            </Typography.Text>
            <Switch
              checked={idSort}
              label={t('使用ID排序')}
              aria-label={t('是否用ID排序')}
              onChange={(v) => {
                localStorage.setItem('id-sort', v + '');
                setIdSort(v);
                loadChannels(0, pageSize, v, enableTagMode)
                  .then()
                  .catch((reason) => {
                    showError(reason);
                  });
              }}
            ></Switch>
          </div>

          <div
            style={{
              display: 'flex',
              flexWrap: 'wrap',
              gap: '8px',
            }}
          >
            <Button
              theme='light'
              type='primary'
              icon={<IconPlus />}
              onClick={() => {
                setEditingChannel({
                  id: undefined,
                });
                setShowEdit(true);
              }}
            >
              {t('添加渠道')}
            </Button>

            <Button
              theme='light'
              type='primary'
              icon={<IconRefresh />}
              onClick={refresh}
            >
              {t('刷新')}
            </Button>

            <Dropdown
              trigger='click'
              render={
                <Dropdown.Menu>
                  <Dropdown.Item>
                    <Popconfirm
                      title={t('确定?')}
                      okType={'warning'}
                      onConfirm={testAllChannels}
                      position={isMobile() ? 'top' : 'top'}
                    >
                      <Button
                        theme='light'
                        type='warning'
                        style={{ width: '100%' }}
                      >
                        {t('测试所有通道')}
                      </Button>
                    </Popconfirm>
                  </Dropdown.Item>
                  <Dropdown.Item>
                    <Popconfirm
                      title={t('确定?')}
                      okType={'secondary'}
                      onConfirm={updateAllChannelsBalance}
                    >
                      <Button
                        theme='light'
                        type='secondary'
                        style={{ width: '100%' }}
                      >
                        {t('更新所有已启用通道余额')}
                      </Button>
                    </Popconfirm>
                  </Dropdown.Item>
                  <Dropdown.Item>
                    <Popconfirm
                      title={t('确定是否要删除禁用通道?')}
                      content={t('此修改将不可逆')}
                      okType={'danger'}
                      onConfirm={deleteAllDisabledChannels}
                    >
                      <Button
                        theme='light'
                        type='danger'
                        style={{ width: '100%' }}
                      >
                        {t('删除禁用通道')}
                      </Button>
                    </Popconfirm>
                  </Dropdown.Item>
                </Dropdown.Menu>
              }
            >
              <Button theme='light' type='tertiary' icon={<IconSetting />}>
                {t('批量操作')}
              </Button>
            </Dropdown>
          </div>
        </Space>
      </div>
      <div
        style={{
          marginTop: 20,
          display: 'flex',
          flexDirection: isMobile() ? 'column' : 'row',
          alignItems: isMobile() ? 'flex-start' : 'center',
          gap: isMobile() ? '8px' : '16px',
        }}
      >
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            marginBottom: isMobile() ? 8 : 0,
          }}
        >
          <Typography.Text strong style={{ marginRight: 8 }}>
            {t('开启批量操作')}
          </Typography.Text>
          <Switch
            label={t('开启批量操作')}
            aria-label={t('是否开启批量操作')}
            onChange={(v) => {
              setEnableBatchDelete(v);
            }}
          />
        </div>

        <div
          style={{
            display: 'flex',
            flexWrap: 'wrap',
            gap: '8px',
          }}
        >
          <Popconfirm
            title={t('确定是否要删除所选通道?')}
            content={t('此修改将不可逆')}
            okType={'danger'}
            onConfirm={batchDeleteChannels}
            disabled={!enableBatchDelete}
          >
            <Button disabled={!enableBatchDelete} theme='light' type='danger'>
              {t('删除所选通道')}
            </Button>
          </Popconfirm>
          <Popconfirm
            title={t('确定是否要修复数据库一致性?')}
            content={t(
              '进行该操作时可能导致渠道访问错误请仅在数据库出现问题时使用',
            )}
            okType={'warning'}
            onConfirm={fixChannelsAbilities}
          >
            <Button theme='light' type='secondary'>
              {t('修复数据库一致性')}
            </Button>
          </Popconfirm>
        </div>
      </div>

      <div
        style={{
          marginTop: 20,
          marginBottom: 20,
          display: 'flex',
          flexDirection: isMobile() ? 'column' : 'row',
          alignItems: isMobile() ? 'flex-start' : 'center',
          gap: isMobile() ? '8px' : '16px',
        }}
      >
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            marginBottom: isMobile() ? 8 : 0,
          }}
        >
          <Typography.Text strong style={{ marginRight: 8 }}>
            {t('标签聚合模式')}
          </Typography.Text>
          <Switch
            checked={enableTagMode}
            label={t('标签聚合模式')}
            aria-label={t('是否启用标签聚合')}
            onChange={(v) => {
              setEnableTagMode(v);
              loadChannels(0, pageSize, idSort, v);
            }}
          />
        </div>

        <div
          style={{
            display: 'flex',
            flexWrap: 'wrap',
            gap: '8px',
          }}
        >
          <Button
            disabled={!enableBatchDelete}
            theme='light'
            type='primary'
            onClick={() => setShowBatchSetTag(true)}
          >
            {t('批量设置标签')}
          </Button>

          <Button
            theme='light'
            type='tertiary'
            icon={<IconSetting />}
            onClick={() => setShowColumnSelector(true)}
          >
            {t('列设置')}
          </Button>
        </div>
      </div>

      <Table
        loading={loading}
        columns={getVisibleColumns()}
        dataSource={pageData}
        rowKey="rowKey"
        pagination={{
          currentPage: activePage,
          pageSize: pageSize,
          total: channelCount,
          pageSizeOpts: [10, 20, 50, 100],
          showSizeChanger: true,
          formatPageText: (page) => '',
          onPageSizeChange: (size) => {
            handlePageSizeChange(size).then();
          },
          onPageChange: handlePageChange,
        }}
        expandAllRows={false}
        onRow={handleRow}
        rowSelection={
          enableBatchDelete
            ? {
                onChange: (selectedRowKeys, selectedRows) => {
                  // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
                  setSelectedChannels(selectedRows);
                },
              }
            : null
        }
      />
      <Modal
        title={t('批量设置标签')}
        visible={showBatchSetTag}
        onOk={batchSetChannelTag}
        onCancel={() => setShowBatchSetTag(false)}
        maskClosable={false}
        centered={true}
        style={{ width: isMobile() ? '90%' : 500 }}
      >
        <div style={{ marginBottom: 20 }}>
          <Typography.Text>{t('请输入要设置的标签名称')}</Typography.Text>
        </div>
        <Input
          placeholder={t('请输入标签名称')}
          value={batchSetTagValue}
          onChange={(v) => setBatchSetTagValue(v)}
          size='large'
        />
        <div style={{ marginTop: 16 }}>
          <Typography.Text type='secondary'>
            {t('已选择 {{count}} 个渠道', { count: selectedChannels.length })}
          </Typography.Text>
        </div>
      </Modal>

      {/* 模型测试弹窗 */}
      <Modal
        title={t('模型测试')}
        visible={showModelTestModal && currentTestChannel !== null}
        onCancel={handleModelTestModalClose}
        footer={null}
        maskClosable={true}
        centered={true}
        width={800}
      >
        <div style={{ 
          maxHeight: '70vh', 
          overflowY: 'auto'
        }}>
          {currentTestChannel && (
            <ModelTestContent
              channel={currentTestChannel}
              isBatchTesting={isBatchTesting}
              concurrentLimit={concurrentLimit}
              setConcurrentLimit={setConcurrentLimit}
              testAllModels={testAllModels}
              modelSearchKeyword={modelSearchKeyword}
              setModelSearchKeyword={setModelSearchKeyword}
              batchTestResults={batchTestResults}
              retryFailedModels={retryFailedModels}
              handleDeleteFailedModels={handleDeleteFailedModels}
              testProgress={testProgress}
              currentTestingModel={currentTestingModel}
              testChannel={testChannel}
              showSuccess={showSuccess}
              showError={showError}
              t={t}
            />
          )}
        </div>
      </Modal>


    </>
  );
};

export default ChannelsTable;