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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
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
/*
Copyright (C) 2025 QuantumNous

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

For commercial licensing, please contact support@quantumnous.com
*/

import React, { useEffect, useState, useRef, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import {
  API,
  showError,
  showInfo,
  showSuccess,
  verifyJSON,
} from '../../../../helpers';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import { CHANNEL_OPTIONS } from '../../../../constants';
import {
  SideSheet,
  Space,
  Spin,
  Button,
  Typography,
  Checkbox,
  Banner,
  Modal,
  ImagePreview,
  Card,
  Tag,
  Avatar,
  Form,
  Row,
  Col,
  Highlight,
  Input,
} from '@douyinfe/semi-ui';
import {
  getChannelModels,
  copy,
  getChannelIcon,
  getModelCategories,
  selectFilter,
} from '../../../../helpers';
import ModelSelectModal from './ModelSelectModal';
import JSONEditor from '../../../common/ui/JSONEditor';
import SecureVerificationModal from '../../../common/modals/SecureVerificationModal';
import ChannelKeyDisplay from '../../../common/ui/ChannelKeyDisplay';
import { useSecureVerification } from '../../../../hooks/common/useSecureVerification';
import { createApiCalls } from '../../../../services/secureVerification';
import {
  IconSave,
  IconClose,
  IconServer,
  IconSetting,
  IconCode,
  IconGlobe,
  IconBolt,
  IconChevronUp,
  IconChevronDown,
} from '@douyinfe/semi-icons';

const { Text, Title } = Typography;

const MODEL_MAPPING_EXAMPLE = {
  'gpt-3.5-turbo': 'gpt-3.5-turbo-0125',
};

const STATUS_CODE_MAPPING_EXAMPLE = {
  400: '500',
};

const REGION_EXAMPLE = {
  default: 'global',
  'gemini-1.5-pro-002': 'europe-west2',
  'gemini-1.5-flash-002': 'europe-west2',
  'claude-3-5-sonnet-20240620': 'europe-west1',
};

// 支持并且已适配通过接口获取模型列表的渠道类型
const MODEL_FETCHABLE_TYPES = new Set([
  1, 4, 14, 34, 17, 26, 27, 24, 47, 25, 20, 23, 31, 35, 40, 42, 48, 43,
]);

function type2secretPrompt(type) {
  // inputs.type === 15 ? '按照如下格式输入:APIKey|SecretKey' : (inputs.type === 18 ? '按照如下格式输入:APPID|APISecret|APIKey' : '请输入渠道对应的鉴权密钥')
  switch (type) {
    case 15:
      return '按照如下格式输入:APIKey|SecretKey';
    case 18:
      return '按照如下格式输入:APPID|APISecret|APIKey';
    case 22:
      return '按照如下格式输入:APIKey-AppId,例如:fastgpt-0sp2gtvfdgyi4k30jwlgwf1i-64f335d84283f05518e9e041';
    case 23:
      return '按照如下格式输入:AppId|SecretId|SecretKey';
    case 33:
      return '按照如下格式输入:Ak|Sk|Region';
    case 45:
        return '请输入渠道对应的鉴权密钥, 豆包语音输入:AppId|AccessToken';
    case 50:
      return '按照如下格式输入: AccessKey|SecretKey, 如果上游是New API,则直接输ApiKey';
    case 51:
      return '按照如下格式输入: AccessKey|SecretAccessKey';
    default:
      return '请输入渠道对应的鉴权密钥';
  }
}

const EditChannelModal = (props) => {
  const { t } = useTranslation();
  const channelId = props.editingChannel.id;
  const isEdit = channelId !== undefined;
  const [loading, setLoading] = useState(isEdit);
  const isMobile = useIsMobile();
  const handleCancel = () => {
    props.handleClose();
  };
  const originInputs = {
    name: '',
    type: 1,
    key: '',
    openai_organization: '',
    max_input_tokens: 0,
    base_url: '',
    other: '',
    model_mapping: '',
    status_code_mapping: '',
    models: [],
    auto_ban: 1,
    test_model: '',
    groups: ['default'],
    priority: 0,
    weight: 0,
    tag: '',
    multi_key_mode: 'random',
    // 渠道额外设置的默认值
    force_format: false,
    thinking_to_content: false,
    proxy: '',
    pass_through_body_enabled: false,
    system_prompt: '',
    system_prompt_override: false,
    settings: '',
    // 仅 Vertex: 密钥格式(存入 settings.vertex_key_type)
    vertex_key_type: 'json',
    // 仅 AWS: 密钥格式和区域(存入 settings.aws_key_type 和 settings.aws_region)
    aws_key_type: 'ak_sk',
    // 企业账户设置
    is_enterprise_account: false,
    // 字段透传控制默认值
    allow_service_tier: false,
    disable_store: false, // false = 允许透传(默认开启)
    allow_safety_identifier: false,
  };
  const [batch, setBatch] = useState(false);
  const [multiToSingle, setMultiToSingle] = useState(false);
  const [multiKeyMode, setMultiKeyMode] = useState('random');
  const [autoBan, setAutoBan] = useState(true);
  const [inputs, setInputs] = useState(originInputs);
  const [originModelOptions, setOriginModelOptions] = useState([]);
  const [modelOptions, setModelOptions] = useState([]);
  const [groupOptions, setGroupOptions] = useState([]);
  const [basicModels, setBasicModels] = useState([]);
  const [fullModels, setFullModels] = useState([]);
  const [modelGroups, setModelGroups] = useState([]);
  const [customModel, setCustomModel] = useState('');
  const [modalImageUrl, setModalImageUrl] = useState('');
  const [isModalOpenurl, setIsModalOpenurl] = useState(false);
  const [modelModalVisible, setModelModalVisible] = useState(false);
  const [fetchedModels, setFetchedModels] = useState([]);
  const formApiRef = useRef(null);
  const [vertexKeys, setVertexKeys] = useState([]);
  const [vertexFileList, setVertexFileList] = useState([]);
  const vertexErroredNames = useRef(new Set()); // 避免重复报错
  const [isMultiKeyChannel, setIsMultiKeyChannel] = useState(false);
  const [channelSearchValue, setChannelSearchValue] = useState('');
  const [useManualInput, setUseManualInput] = useState(false); // 是否使用手动输入模式
  const [keyMode, setKeyMode] = useState('append'); // 密钥模式:replace(覆盖)或 append(追加)
  const [isEnterpriseAccount, setIsEnterpriseAccount] = useState(false); // 是否为企业账户
  const [doubaoApiEditUnlocked, setDoubaoApiEditUnlocked] = useState(false); // 豆包渠道自定义 API 地址隐藏入口
  const redirectModelList = useMemo(() => {
    const mapping = inputs.model_mapping;
    if (typeof mapping !== 'string') return [];
    const trimmed = mapping.trim();
    if (!trimmed) return [];
    try {
      const parsed = JSON.parse(trimmed);
      if (
        !parsed ||
        typeof parsed !== 'object' ||
        Array.isArray(parsed)
      ) {
        return [];
      }
      const values = Object.values(parsed)
        .map((value) =>
          typeof value === 'string' ? value.trim() : undefined,
        )
        .filter((value) => value);
      return Array.from(new Set(values));
    } catch (error) {
      return [];
    }
  }, [inputs.model_mapping]);

  // 密钥显示状态
  const [keyDisplayState, setKeyDisplayState] = useState({
    showModal: false,
    keyData: '',
  });

  // 专门的2FA验证状态(用于TwoFactorAuthModal)
  const [show2FAVerifyModal, setShow2FAVerifyModal] = useState(false);
  const [verifyCode, setVerifyCode] = useState('');
  const [verifyLoading, setVerifyLoading] = useState(false);

  // 表单块导航相关状态
  const formSectionRefs = useRef({
    basicInfo: null,
    apiConfig: null,
    modelConfig: null,
    advancedSettings: null,
    channelExtraSettings: null,
  });
  const [currentSectionIndex, setCurrentSectionIndex] = useState(0);
  const formSections = [
    'basicInfo',
    'apiConfig',
    'modelConfig',
    'advancedSettings',
    'channelExtraSettings',
  ];
  const formContainerRef = useRef(null);
  const doubaoApiClickCountRef = useRef(0);
  const initialModelsRef = useRef([]);
  const initialModelMappingRef = useRef('');

  // 2FA状态更新辅助函数
  const updateTwoFAState = (updates) => {
    setTwoFAState((prev) => ({ ...prev, ...updates }));
  };
  // 使用通用安全验证 Hook
  const {
    isModalVisible,
    verificationMethods,
    verificationState,
    withVerification,
    executeVerification,
    cancelVerification,
    setVerificationCode,
    switchVerificationMethod,
  } = useSecureVerification({
    onSuccess: (result) => {
      // 验证成功后显示密钥
      console.log('Verification success, result:', result);
      if (result && result.success && result.data?.key) {
        showSuccess(t('密钥获取成功'));
        setKeyDisplayState({
          showModal: true,
          keyData: result.data.key,
        });
      } else if (result && result.key) {
        // 直接返回了 key(没有包装在 data 中)
        showSuccess(t('密钥获取成功'));
        setKeyDisplayState({
          showModal: true,
          keyData: result.key,
        });
      }
    },
  });

  // 重置密钥显示状态
  const resetKeyDisplayState = () => {
    setKeyDisplayState({
      showModal: false,
      keyData: '',
    });
  };

  // 重置2FA验证状态
  const reset2FAVerifyState = () => {
    setShow2FAVerifyModal(false);
    setVerifyCode('');
    setVerifyLoading(false);
  };

  // 表单导航功能
  const scrollToSection = (sectionKey) => {
    const sectionElement = formSectionRefs.current[sectionKey];
    if (sectionElement) {
      sectionElement.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
        inline: 'nearest',
      });
    }
  };

  const navigateToSection = (direction) => {
    const availableSections = formSections.filter((section) => {
      if (section === 'apiConfig') {
        return showApiConfigCard;
      }
      return true;
    });

    let newIndex;
    if (direction === 'up') {
      newIndex =
        currentSectionIndex > 0
          ? currentSectionIndex - 1
          : availableSections.length - 1;
    } else {
      newIndex =
        currentSectionIndex < availableSections.length - 1
          ? currentSectionIndex + 1
          : 0;
    }

    setCurrentSectionIndex(newIndex);
    scrollToSection(availableSections[newIndex]);
  };

  const handleApiConfigSecretClick = () => {
    if (inputs.type !== 45) return;
    const next = doubaoApiClickCountRef.current + 1;
    doubaoApiClickCountRef.current = next;
    if (next >= 10) {
      setDoubaoApiEditUnlocked((unlocked) => {
        if (!unlocked) {
          showInfo(t('已解锁豆包自定义 API 地址编辑'));
        }
        return true;
      });
    }
  };

  // 渠道额外设置状态
  const [channelSettings, setChannelSettings] = useState({
    force_format: false,
    thinking_to_content: false,
    proxy: '',
    pass_through_body_enabled: false,
    system_prompt: '',
  });
  const showApiConfigCard = true; // 控制是否显示 API 配置卡片
  const getInitValues = () => ({ ...originInputs });

  // 处理渠道额外设置的更新
  const handleChannelSettingsChange = (key, value) => {
    // 更新内部状态
    setChannelSettings((prev) => ({ ...prev, [key]: value }));

    // 同步更新到表单字段
    if (formApiRef.current) {
      formApiRef.current.setValue(key, value);
    }

    // 同步更新inputs状态
    setInputs((prev) => ({ ...prev, [key]: value }));

    // 生成setting JSON并更新
    const newSettings = { ...channelSettings, [key]: value };
    const settingsJson = JSON.stringify(newSettings);
    handleInputChange('setting', settingsJson);
  };

  const handleChannelOtherSettingsChange = (key, value) => {
    // 更新内部状态
    setChannelSettings((prev) => ({ ...prev, [key]: value }));

    // 同步更新到表单字段
    if (formApiRef.current) {
      formApiRef.current.setValue(key, value);
    }

    // 同步更新inputs状态
    setInputs((prev) => ({ ...prev, [key]: value }));

    // 需要更新settings,是一个json,例如{"azure_responses_version": "preview"}
    let settings = {};
    if (inputs.settings) {
      try {
        settings = JSON.parse(inputs.settings);
      } catch (error) {
        console.error('解析设置失败:', error);
      }
    }
    settings[key] = value;
    const settingsJson = JSON.stringify(settings);
    handleInputChange('settings', settingsJson);
  };

  const handleInputChange = (name, value) => {
    if (formApiRef.current) {
      formApiRef.current.setValue(name, value);
    }
    if (name === 'models' && Array.isArray(value)) {
      value = Array.from(new Set(value.map((m) => (m || '').trim())));
    }

    if (name === 'base_url' && value.endsWith('/v1')) {
      Modal.confirm({
        title: '警告',
        content:
          '不需要在末尾加/v1,New API会自动处理,添加后可能导致请求失败,是否继续?',
        onOk: () => {
          setInputs((inputs) => ({ ...inputs, [name]: value }));
        },
      });
      return;
    }
    setInputs((inputs) => ({ ...inputs, [name]: value }));
    if (name === 'type') {
      let localModels = [];
      switch (value) {
        case 2:
          localModels = [
            'mj_imagine',
            'mj_variation',
            'mj_reroll',
            'mj_blend',
            'mj_upscale',
            'mj_describe',
            'mj_uploads',
          ];
          break;
        case 5:
          localModels = [
            'swap_face',
            'mj_imagine',
            'mj_video',
            'mj_edits',
            'mj_variation',
            'mj_reroll',
            'mj_blend',
            'mj_upscale',
            'mj_describe',
            'mj_zoom',
            'mj_shorten',
            'mj_modal',
            'mj_inpaint',
            'mj_custom_zoom',
            'mj_high_variation',
            'mj_low_variation',
            'mj_pan',
            'mj_uploads',
          ];
          break;
        case 36:
          localModels = ['suno_music', 'suno_lyrics'];
          break;
        case 45:
          localModels = getChannelModels(value);
          setInputs((prevInputs) => ({
            ...prevInputs,
            base_url: 'https://ark.cn-beijing.volces.com',
          }));
          break;
        default:
          localModels = getChannelModels(value);
          break;
      }
      if (inputs.models.length === 0) {
        setInputs((inputs) => ({ ...inputs, models: localModels }));
      }
      setBasicModels(localModels);

      // 重置手动输入模式状态
      setUseManualInput(false);
    }
    //setAutoBan
  };

  const loadChannel = async () => {
    setLoading(true);
    let res = await API.get(`/api/channel/${channelId}`);
    if (res === undefined) {
      return;
    }
    const { success, message, data } = res.data;
    if (success) {
      if (data.models === '') {
        data.models = [];
      } else {
        data.models = data.models.split(',');
      }
      if (data.group === '') {
        data.groups = [];
      } else {
        data.groups = data.group.split(',');
      }
      if (data.model_mapping !== '') {
        data.model_mapping = JSON.stringify(
          JSON.parse(data.model_mapping),
          null,
          2,
        );
      }
      const chInfo = data.channel_info || {};
      const isMulti = chInfo.is_multi_key === true;
      setIsMultiKeyChannel(isMulti);
      if (isMulti) {
        setBatch(true);
        setMultiToSingle(true);
        const modeVal = chInfo.multi_key_mode || 'random';
        setMultiKeyMode(modeVal);
        data.multi_key_mode = modeVal;
      } else {
        setBatch(false);
        setMultiToSingle(false);
      }
      // 解析渠道额外设置并合并到data中
      if (data.setting) {
        try {
          const parsedSettings = JSON.parse(data.setting);
          data.force_format = parsedSettings.force_format || false;
          data.thinking_to_content =
            parsedSettings.thinking_to_content || false;
          data.proxy = parsedSettings.proxy || '';
          data.pass_through_body_enabled =
            parsedSettings.pass_through_body_enabled || false;
          data.system_prompt = parsedSettings.system_prompt || '';
          data.system_prompt_override =
            parsedSettings.system_prompt_override || false;
        } catch (error) {
          console.error('解析渠道设置失败:', error);
          data.force_format = false;
          data.thinking_to_content = false;
          data.proxy = '';
          data.pass_through_body_enabled = false;
          data.system_prompt = '';
          data.system_prompt_override = false;
        }
      } else {
        data.force_format = false;
        data.thinking_to_content = false;
        data.proxy = '';
        data.pass_through_body_enabled = false;
        data.system_prompt = '';
        data.system_prompt_override = false;
      }

      if (data.settings) {
        try {
          const parsedSettings = JSON.parse(data.settings);
          data.azure_responses_version =
            parsedSettings.azure_responses_version || '';
          // 读取 Vertex 密钥格式
          data.vertex_key_type = parsedSettings.vertex_key_type || 'json';
          // 读取 AWS 密钥格式和区域
          data.aws_key_type = parsedSettings.aws_key_type || 'ak_sk';
          // 读取企业账户设置
          data.is_enterprise_account =
            parsedSettings.openrouter_enterprise === true;
          // 读取字段透传控制设置
          data.allow_service_tier = parsedSettings.allow_service_tier || false;
          data.disable_store = parsedSettings.disable_store || false;
          data.allow_safety_identifier =
            parsedSettings.allow_safety_identifier || false;
        } catch (error) {
          console.error('解析其他设置失败:', error);
          data.azure_responses_version = '';
          data.region = '';
          data.vertex_key_type = 'json';
          data.aws_key_type = 'ak_sk';
          data.is_enterprise_account = false;
          data.allow_service_tier = false;
          data.disable_store = false;
          data.allow_safety_identifier = false;
        }
      } else {
        // 兼容历史数据:老渠道没有 settings 时,默认按 json 展示
        data.vertex_key_type = 'json';
        data.aws_key_type = 'ak_sk';
        data.is_enterprise_account = false;
        data.allow_service_tier = false;
        data.disable_store = false;
        data.allow_safety_identifier = false;
      }

      if (
        data.type === 45 &&
        (!data.base_url ||
          (typeof data.base_url === 'string' && data.base_url.trim() === ''))
      ) {
        data.base_url = 'https://ark.cn-beijing.volces.com';
      }

      setInputs(data);
      if (formApiRef.current) {
        formApiRef.current.setValues(data);
      }
      if (data.auto_ban === 0) {
        setAutoBan(false);
      } else {
        setAutoBan(true);
      }
      // 同步企业账户状态
      setIsEnterpriseAccount(data.is_enterprise_account || false);
      setBasicModels(getChannelModels(data.type));
      // 同步更新channelSettings状态显示
      setChannelSettings({
        force_format: data.force_format,
        thinking_to_content: data.thinking_to_content,
        proxy: data.proxy,
        pass_through_body_enabled: data.pass_through_body_enabled,
        system_prompt: data.system_prompt,
        system_prompt_override: data.system_prompt_override || false,
      });
      initialModelsRef.current = (data.models || [])
        .map((model) => (model || '').trim())
        .filter(Boolean);
      initialModelMappingRef.current = data.model_mapping || '';
      // console.log(data);
    } else {
      showError(message);
    }
    setLoading(false);
  };

  const fetchUpstreamModelList = async (name) => {
    // if (inputs['type'] !== 1) {
    //   showError(t('仅支持 OpenAI 接口格式'));
    //   return;
    // }
    setLoading(true);
    const models = [];
    let err = false;

    if (isEdit) {
      // 如果是编辑模式,使用已有的 channelId 获取模型列表
      const res = await API.get('/api/channel/fetch_models/' + channelId, {
        skipErrorHandler: true,
      });
      if (res && res.data && res.data.success) {
        models.push(...res.data.data);
      } else {
        err = true;
      }
    } else {
      // 如果是新建模式,通过后端代理获取模型列表
      if (!inputs?.['key']) {
        showError(t('请填写密钥'));
        err = true;
      } else {
        try {
          const res = await API.post(
            '/api/channel/fetch_models',
            {
              base_url: inputs['base_url'],
              type: inputs['type'],
              key: inputs['key'],
            },
            { skipErrorHandler: true },
          );

          if (res && res.data && res.data.success) {
            models.push(...res.data.data);
          } else {
            err = true;
          }
        } catch (error) {
          console.error('Error fetching models:', error);
          err = true;
        }
      }
    }

    if (!err) {
      const uniqueModels = Array.from(new Set(models));
      setFetchedModels(uniqueModels);
      setModelModalVisible(true);
    } else {
      showError(t('获取模型列表失败'));
    }
    setLoading(false);
  };

  const fetchModels = async () => {
    try {
      let res = await API.get(`/api/channel/models`);
      const localModelOptions = res.data.data.map((model) => {
        const id = (model.id || '').trim();
        return {
          key: id,
          label: id,
          value: id,
        };
      });
      setOriginModelOptions(localModelOptions);
      setFullModels(res.data.data.map((model) => model.id));
      setBasicModels(
        res.data.data
          .filter((model) => {
            return model.id.startsWith('gpt-') || model.id.startsWith('text-');
          })
          .map((model) => model.id),
      );
    } catch (error) {
      showError(error.message);
    }
  };

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

  const fetchModelGroups = async () => {
    try {
      const res = await API.get('/api/prefill_group?type=model');
      if (res?.data?.success) {
        setModelGroups(res.data.data || []);
      }
    } catch (error) {
      // ignore
    }
  };

  // 查看渠道密钥(透明验证)
  const handleShow2FAModal = async () => {
    try {
      // 使用 withVerification 包装,会自动处理需要验证的情况
      const result = await withVerification(
        createApiCalls.viewChannelKey(channelId),
        {
          title: t('查看渠道密钥'),
          description: t('为了保护账户安全,请验证您的身份。'),
          preferredMethod: 'passkey', // 优先使用 Passkey
        },
      );

      // 如果直接返回了结果(已验证),显示密钥
      if (result && result.success && result.data?.key) {
        showSuccess(t('密钥获取成功'));
        setKeyDisplayState({
          showModal: true,
          keyData: result.data.key,
        });
      }
    } catch (error) {
      console.error('Failed to view channel key:', error);
      showError(error.message || t('获取密钥失败'));
    }
  };

  useEffect(() => {
    if (inputs.type !== 45) {
      doubaoApiClickCountRef.current = 0;
      setDoubaoApiEditUnlocked(false);
    }
  }, [inputs.type]);

  useEffect(() => {
    const modelMap = new Map();

    originModelOptions.forEach((option) => {
      const v = (option.value || '').trim();
      if (!modelMap.has(v)) {
        modelMap.set(v, option);
      }
    });

    inputs.models.forEach((model) => {
      const v = (model || '').trim();
      if (!modelMap.has(v)) {
        modelMap.set(v, {
          key: v,
          label: v,
          value: v,
        });
      }
    });

    const categories = getModelCategories(t);
    const optionsWithIcon = Array.from(modelMap.values()).map((opt) => {
      const modelName = opt.value;
      let icon = null;
      for (const [key, category] of Object.entries(categories)) {
        if (key !== 'all' && category.filter({ model_name: modelName })) {
          icon = category.icon;
          break;
        }
      }
      return {
        ...opt,
        label: (
          <span className='flex items-center gap-1'>
            {icon}
            {modelName}
          </span>
        ),
      };
    });

    setModelOptions(optionsWithIcon);
  }, [originModelOptions, inputs.models, t]);

  useEffect(() => {
    fetchModels().then();
    fetchGroups().then();
    if (!isEdit) {
      setInputs(originInputs);
      if (formApiRef.current) {
        formApiRef.current.setValues(originInputs);
      }
      let localModels = getChannelModels(inputs.type);
      setBasicModels(localModels);
      setInputs((inputs) => ({ ...inputs, models: localModels }));
    }
  }, [props.editingChannel.id]);

  useEffect(() => {
    if (formApiRef.current) {
      formApiRef.current.setValues(inputs);
    }
  }, [inputs]);

  useEffect(() => {
    if (props.visible) {
      if (isEdit) {
        loadChannel();
      } else {
        formApiRef.current?.setValues(getInitValues());
      }
      fetchModelGroups();
      // 重置手动输入模式状态
      setUseManualInput(false);
      // 重置导航状态
      setCurrentSectionIndex(0);
    } else {
      // 统一的模态框关闭重置逻辑
      resetModalState();
    }
  }, [props.visible, channelId]);

  useEffect(() => {
    if (!isEdit) {
      initialModelsRef.current = [];
      initialModelMappingRef.current = '';
    }
  }, [isEdit, props.visible]);

  // 统一的模态框重置函数
  const resetModalState = () => {
    formApiRef.current?.reset();
    // 重置渠道设置状态
    setChannelSettings({
      force_format: false,
      thinking_to_content: false,
      proxy: '',
      pass_through_body_enabled: false,
      system_prompt: '',
      system_prompt_override: false,
    });
    // 重置密钥模式状态
    setKeyMode('append');
    // 重置企业账户状态
    setIsEnterpriseAccount(false);
    // 重置豆包隐藏入口状态
    setDoubaoApiEditUnlocked(false);
    doubaoApiClickCountRef.current = 0;
    // 清空表单中的key_mode字段
    if (formApiRef.current) {
      formApiRef.current.setValue('key_mode', undefined);
    }
    // 重置本地输入,避免下次打开残留上一次的 JSON 字段值
    setInputs(getInitValues());
    // 重置密钥显示状态
    resetKeyDisplayState();
  };

  const handleVertexUploadChange = ({ fileList }) => {
    vertexErroredNames.current.clear();
    (async () => {
      let validFiles = [];
      let keys = [];
      const errorNames = [];
      for (const item of fileList) {
        const fileObj = item.fileInstance;
        if (!fileObj) continue;
        try {
          const txt = await fileObj.text();
          keys.push(JSON.parse(txt));
          validFiles.push(item);
        } catch (err) {
          if (!vertexErroredNames.current.has(item.name)) {
            errorNames.push(item.name);
            vertexErroredNames.current.add(item.name);
          }
        }
      }

      // 非批量模式下只保留一个文件(最新选择的),避免重复叠加
      if (!batch && validFiles.length > 1) {
        validFiles = [validFiles[validFiles.length - 1]];
        keys = [keys[keys.length - 1]];
      }

      setVertexKeys(keys);
      setVertexFileList(validFiles);
      if (formApiRef.current) {
        formApiRef.current.setValue('vertex_files', validFiles);
      }
      setInputs((prev) => ({ ...prev, vertex_files: validFiles }));

      if (errorNames.length > 0) {
        showError(
          t('以下文件解析失败,已忽略:{{list}}', {
            list: errorNames.join(', '),
          }),
        );
      }
    })();
  };

  const confirmMissingModelMappings = (missingModels) =>
    new Promise((resolve) => {
      const modal = Modal.confirm({
        title: t('模型未加入列表,可能无法调用'),
        content: (
          <div className='text-sm leading-6'>
            <div>
              {t(
                '模型重定向里的下列模型尚未添加到“模型”列表,调用时会因为缺少可用模型而失败:',
              )}
            </div>
            <div className='font-mono text-xs break-all text-red-600 mt-1'>
              {missingModels.join(', ')}
            </div>
            <div className='mt-2'>
              {t(
                '你可以在“自定义模型名称”处手动添加它们,然后点击填入后再提交,或者直接使用下方操作自动处理。',
              )}
            </div>
          </div>
        ),
        centered: true,
        footer: (
          <Space align='center' className='w-full justify-end'>
            <Button
              type='tertiary'
              onClick={() => {
                modal.destroy();
                resolve('cancel');
              }}
            >
              {t('返回修改')}
            </Button>
            <Button
              type='primary'
              theme='light'
              onClick={() => {
                modal.destroy();
                resolve('submit');
              }}
            >
              {t('直接提交')}
            </Button>
            <Button
              type='primary'
              theme='solid'
              onClick={() => {
                modal.destroy();
                resolve('add');
              }}
            >
              {t('添加后提交')}
            </Button>
          </Space>
        ),
      });
    });

  const hasModelConfigChanged = (normalizedModels, modelMappingStr) => {
    if (!isEdit) return true;
    const initialModels = initialModelsRef.current;
    if (normalizedModels.length !== initialModels.length) {
      return true;
    }
    for (let i = 0; i < normalizedModels.length; i++) {
      if (normalizedModels[i] !== initialModels[i]) {
        return true;
      }
    }
    const normalizedMapping = (modelMappingStr || '').trim();
    const initialMapping = (initialModelMappingRef.current || '').trim();
    return normalizedMapping !== initialMapping;
  };

  const submit = async () => {
    const formValues = formApiRef.current ? formApiRef.current.getValues() : {};
    let localInputs = { ...formValues };

    if (localInputs.type === 41) {
      const keyType = localInputs.vertex_key_type || 'json';
      if (keyType === 'api_key') {
        // 直接作为普通字符串密钥处理
        if (!isEdit && (!localInputs.key || localInputs.key.trim() === '')) {
          showInfo(t('请输入密钥!'));
          return;
        }
      } else {
        // JSON 服务账号密钥
        if (useManualInput) {
          if (localInputs.key && localInputs.key.trim() !== '') {
            try {
              const parsedKey = JSON.parse(localInputs.key);
              localInputs.key = JSON.stringify(parsedKey);
            } catch (err) {
              showError(t('密钥格式无效,请输入有效的 JSON 格式密钥'));
              return;
            }
          } else if (!isEdit) {
            showInfo(t('请输入密钥!'));
            return;
          }
        } else {
          // 文件上传模式
          let keys = vertexKeys;
          if (keys.length === 0 && vertexFileList.length > 0) {
            try {
              const parsed = await Promise.all(
                vertexFileList.map(async (item) => {
                  const fileObj = item.fileInstance;
                  if (!fileObj) return null;
                  const txt = await fileObj.text();
                  return JSON.parse(txt);
                }),
              );
              keys = parsed.filter(Boolean);
            } catch (err) {
              showError(t('解析密钥文件失败: {{msg}}', { msg: err.message }));
              return;
            }
          }
          if (keys.length === 0) {
            if (!isEdit) {
              showInfo(t('请上传密钥文件!'));
              return;
            } else {
              delete localInputs.key;
            }
          } else {
            localInputs.key = batch
              ? JSON.stringify(keys)
              : JSON.stringify(keys[0]);
          }
        }
      }
    }

    // 如果是编辑模式且 key 为空字符串,避免提交空值覆盖旧密钥
    if (isEdit && (!localInputs.key || localInputs.key.trim() === '')) {
      delete localInputs.key;
    }
    delete localInputs.vertex_files;

    if (!isEdit && (!localInputs.name || !localInputs.key)) {
      showInfo(t('请填写渠道名称和渠道密钥!'));
      return;
    }
    if (!Array.isArray(localInputs.models) || localInputs.models.length === 0) {
      showInfo(t('请至少选择一个模型!'));
      return;
    }
    if (
      localInputs.type === 45 &&
      (!localInputs.base_url || localInputs.base_url.trim() === '')
    ) {
      showInfo(t('请输入API地址!'));
      return;
    }
    const hasModelMapping =
      typeof localInputs.model_mapping === 'string' &&
      localInputs.model_mapping.trim() !== '';
    let parsedModelMapping = null;
    if (hasModelMapping) {
      if (!verifyJSON(localInputs.model_mapping)) {
        showInfo(t('模型映射必须是合法的 JSON 格式!'));
        return;
      }
      try {
        parsedModelMapping = JSON.parse(localInputs.model_mapping);
      } catch (error) {
        showInfo(t('模型映射必须是合法的 JSON 格式!'));
        return;
      }
    }

    const normalizedModels = (localInputs.models || [])
      .map((model) => (model || '').trim())
      .filter(Boolean);
    localInputs.models = normalizedModels;

    if (
      parsedModelMapping &&
      typeof parsedModelMapping === 'object' &&
      !Array.isArray(parsedModelMapping)
    ) {
      const modelSet = new Set(normalizedModels);
      const missingModels = Object.keys(parsedModelMapping)
        .map((key) => (key || '').trim())
        .filter((key) => key && !modelSet.has(key));
      const shouldPromptMissing =
        missingModels.length > 0 &&
        hasModelConfigChanged(normalizedModels, localInputs.model_mapping);
      if (shouldPromptMissing) {
        const confirmAction = await confirmMissingModelMappings(missingModels);
        if (confirmAction === 'cancel') {
          return;
        }
        if (confirmAction === 'add') {
          const updatedModels = Array.from(
            new Set([...normalizedModels, ...missingModels]),
          );
          localInputs.models = updatedModels;
          handleInputChange('models', updatedModels);
        }
      }
    }

    if (localInputs.base_url && localInputs.base_url.endsWith('/')) {
      localInputs.base_url = localInputs.base_url.slice(
        0,
        localInputs.base_url.length - 1,
      );
    }
    if (localInputs.type === 18 && localInputs.other === '') {
      localInputs.other = 'v2.1';
    }

    // 生成渠道额外设置JSON
    const channelExtraSettings = {
      force_format: localInputs.force_format || false,
      thinking_to_content: localInputs.thinking_to_content || false,
      proxy: localInputs.proxy || '',
      pass_through_body_enabled: localInputs.pass_through_body_enabled || false,
      system_prompt: localInputs.system_prompt || '',
      system_prompt_override: localInputs.system_prompt_override || false,
    };
    localInputs.setting = JSON.stringify(channelExtraSettings);

    // 处理 settings 字段(包括企业账户设置和字段透传控制)
    let settings = {};
    if (localInputs.settings) {
      try {
        settings = JSON.parse(localInputs.settings);
      } catch (error) {
        console.error('解析settings失败:', error);
      }
    }

    // type === 20: 设置企业账户标识,无论是true还是false都要传到后端
    if (localInputs.type === 20) {
      settings.openrouter_enterprise =
        localInputs.is_enterprise_account === true;
    }

    // type === 33 (AWS): 保存 aws_key_type 到 settings
    if (localInputs.type === 33) {
      settings.aws_key_type = localInputs.aws_key_type || 'ak_sk';
    }

    // type === 1 (OpenAI) 或 type === 14 (Claude): 设置字段透传控制(显式保存布尔值)
    if (localInputs.type === 1 || localInputs.type === 14) {
      settings.allow_service_tier = localInputs.allow_service_tier === true;
      // 仅 OpenAI 渠道需要 store 和 safety_identifier
      if (localInputs.type === 1) {
        settings.disable_store = localInputs.disable_store === true;
        settings.allow_safety_identifier =
          localInputs.allow_safety_identifier === true;
      }
    }

    localInputs.settings = JSON.stringify(settings);

    // 清理不需要发送到后端的字段
    delete localInputs.force_format;
    delete localInputs.thinking_to_content;
    delete localInputs.proxy;
    delete localInputs.pass_through_body_enabled;
    delete localInputs.system_prompt;
    delete localInputs.system_prompt_override;
    delete localInputs.is_enterprise_account;
    // 顶层的 vertex_key_type 不应发送给后端
    delete localInputs.vertex_key_type;
    // 顶层的 aws_key_type 不应发送给后端
    delete localInputs.aws_key_type;
    // 清理字段透传控制的临时字段
    delete localInputs.allow_service_tier;
    delete localInputs.disable_store;
    delete localInputs.allow_safety_identifier;

    let res;
    localInputs.auto_ban = localInputs.auto_ban ? 1 : 0;
    localInputs.models = localInputs.models.join(',');
    localInputs.group = (localInputs.groups || []).join(',');

    let mode = 'single';
    if (batch) {
      mode = multiToSingle ? 'multi_to_single' : 'batch';
    }

    if (isEdit) {
      res = await API.put(`/api/channel/`, {
        ...localInputs,
        id: parseInt(channelId),
        key_mode: isMultiKeyChannel ? keyMode : undefined, // 只在多key模式下传递
      });
    } else {
      res = await API.post(`/api/channel/`, {
        mode: mode,
        multi_key_mode: mode === 'multi_to_single' ? multiKeyMode : undefined,
        channel: localInputs,
      });
    }
    const { success, message } = res.data;
    if (success) {
      if (isEdit) {
        showSuccess(t('渠道更新成功!'));
      } else {
        showSuccess(t('渠道创建成功!'));
        setInputs(originInputs);
      }
      props.refresh();
      props.handleClose();
    } else {
      showError(message);
    }
  };

  // 密钥去重函数
  const deduplicateKeys = () => {
    const currentKey = formApiRef.current?.getValue('key') || inputs.key || '';

    if (!currentKey.trim()) {
      showInfo(t('请先输入密钥'));
      return;
    }

    // 按行分割密钥
    const keyLines = currentKey.split('\n');
    const beforeCount = keyLines.length;

    // 使用哈希表去重,保持原有顺序
    const keySet = new Set();
    const deduplicatedKeys = [];

    keyLines.forEach((line) => {
      const trimmedLine = line.trim();
      if (trimmedLine && !keySet.has(trimmedLine)) {
        keySet.add(trimmedLine);
        deduplicatedKeys.push(trimmedLine);
      }
    });

    const afterCount = deduplicatedKeys.length;
    const deduplicatedKeyText = deduplicatedKeys.join('\n');

    // 更新表单和状态
    if (formApiRef.current) {
      formApiRef.current.setValue('key', deduplicatedKeyText);
    }
    handleInputChange('key', deduplicatedKeyText);

    // 显示去重结果
    const message = t(
      '去重完成:去重前 {{before}} 个密钥,去重后 {{after}} 个密钥',
      {
        before: beforeCount,
        after: afterCount,
      },
    );

    if (beforeCount === afterCount) {
      showInfo(t('未发现重复密钥'));
    } else {
      showSuccess(message);
    }
  };

  const addCustomModels = () => {
    if (customModel.trim() === '') return;
    const modelArray = customModel.split(',').map((model) => model.trim());

    let localModels = [...inputs.models];
    let localModelOptions = [...modelOptions];
    const addedModels = [];

    modelArray.forEach((model) => {
      if (model && !localModels.includes(model)) {
        localModels.push(model);
        localModelOptions.push({
          key: model,
          label: model,
          value: model,
        });
        addedModels.push(model);
      }
    });

    setModelOptions(localModelOptions);
    setCustomModel('');
    handleInputChange('models', localModels);

    if (addedModels.length > 0) {
      showSuccess(
        t('已新增 {{count}} 个模型:{{list}}', {
          count: addedModels.length,
          list: addedModels.join(', '),
        }),
      );
    } else {
      showInfo(t('未发现新增模型'));
    }
  };

  const batchAllowed = !isEdit || isMultiKeyChannel;
  const batchExtra = batchAllowed ? (
    <Space>
      {!isEdit && (
        <Checkbox
          disabled={isEdit}
          checked={batch}
          onChange={(e) => {
            const checked = e.target.checked;

            if (!checked && vertexFileList.length > 1) {
              Modal.confirm({
                title: t('切换为单密钥模式'),
                content: t(
                  '将仅保留第一个密钥文件,其余文件将被移除,是否继续?',
                ),
                onOk: () => {
                  const firstFile = vertexFileList[0];
                  const firstKey = vertexKeys[0] ? [vertexKeys[0]] : [];

                  setVertexFileList([firstFile]);
                  setVertexKeys(firstKey);

                  formApiRef.current?.setValue('vertex_files', [firstFile]);
                  setInputs((prev) => ({ ...prev, vertex_files: [firstFile] }));

                  setBatch(false);
                  setMultiToSingle(false);
                  setMultiKeyMode('random');
                },
                onCancel: () => {
                  setBatch(true);
                },
                centered: true,
              });
              return;
            }

            setBatch(checked);
            if (!checked) {
              setMultiToSingle(false);
              setMultiKeyMode('random');
            } else {
              // 批量模式下禁用手动输入,并清空手动输入的内容
              setUseManualInput(false);
              if (inputs.type === 41) {
                // 清空手动输入的密钥内容
                if (formApiRef.current) {
                  formApiRef.current.setValue('key', '');
                }
                handleInputChange('key', '');
              }
            }
          }}
        >
          {t('批量创建')}
        </Checkbox>
      )}
      {batch && (
        <>
          <Checkbox
            disabled={isEdit}
            checked={multiToSingle}
            onChange={() => {
              setMultiToSingle((prev) => {
                const nextValue = !prev;
                setInputs((prevInputs) => {
                  const newInputs = { ...prevInputs };
                  if (nextValue) {
                    newInputs.multi_key_mode = multiKeyMode;
                  } else {
                    delete newInputs.multi_key_mode;
                  }
                  return newInputs;
                });
                return nextValue;
              });
            }}
          >
            {t('密钥聚合模式')}
          </Checkbox>

          {inputs.type !== 41 && (
            <Button
              size='small'
              type='tertiary'
              theme='outline'
              onClick={deduplicateKeys}
              style={{ textDecoration: 'underline' }}
            >
              {t('密钥去重')}
            </Button>
          )}
        </>
      )}
    </Space>
  ) : null;

  const channelOptionList = useMemo(
    () =>
      CHANNEL_OPTIONS.map((opt) => ({
        ...opt,
        // 保持 label 为纯文本以支持搜索
        label: opt.label,
      })),
    [],
  );

  const renderChannelOption = (renderProps) => {
    const {
      disabled,
      selected,
      label,
      value,
      focused,
      className,
      style,
      onMouseEnter,
      onClick,
      ...rest
    } = renderProps;

    const searchWords = channelSearchValue ? [channelSearchValue] : [];

    // 构建样式类名
    const optionClassName = [
      'flex items-center gap-3 px-3 py-2 transition-all duration-200 rounded-lg mx-2 my-1',
      focused && 'bg-blue-50 shadow-sm',
      selected &&
        'bg-blue-100 text-blue-700 shadow-lg ring-2 ring-blue-200 ring-opacity-50',
      disabled && 'opacity-50 cursor-not-allowed',
      !disabled && 'hover:bg-gray-50 hover:shadow-md cursor-pointer',
      className,
    ]
      .filter(Boolean)
      .join(' ');

    return (
      <div
        style={style}
        className={optionClassName}
        onClick={() => !disabled && onClick()}
        onMouseEnter={(e) => onMouseEnter()}
      >
        <div className='flex items-center gap-3 w-full'>
          <div className='flex-shrink-0 w-5 h-5 flex items-center justify-center'>
            {getChannelIcon(value)}
          </div>
          <div className='flex-1 min-w-0'>
            <Highlight
              sourceString={label}
              searchWords={searchWords}
              className='text-sm font-medium truncate'
            />
          </div>
          {selected && (
            <div className='flex-shrink-0 text-blue-600'>
              <svg
                width='16'
                height='16'
                viewBox='0 0 16 16'
                fill='currentColor'
              >
                <path d='M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 01-1.06 0L2.22 9.28a.75.75 0 011.06-1.06L6 10.94l6.72-6.72a.75.75 0 011.06 0z' />
              </svg>
            </div>
          )}
        </div>
      </div>
    );
  };

  return (
    <>
      <SideSheet
        placement={isEdit ? 'right' : 'left'}
        title={
          <Space>
            <Tag color='blue' shape='circle'>
              {isEdit ? t('编辑') : t('新建')}
            </Tag>
            <Title heading={4} className='m-0'>
              {isEdit ? t('更新渠道信息') : t('创建新的渠道')}
            </Title>
          </Space>
        }
        bodyStyle={{ padding: '0' }}
        visible={props.visible}
        width={isMobile ? '100%' : 600}
        footer={
          <div className='flex justify-between items-center bg-white'>
            <div className='flex gap-2'>
              <Button
                size='small'
                type='tertiary'
                icon={<IconChevronUp />}
                onClick={() => navigateToSection('up')}
                style={{
                  borderRadius: '50%',
                  width: '32px',
                  height: '32px',
                  padding: 0,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}
                title={t('上一个表单块')}
              />
              <Button
                size='small'
                type='tertiary'
                icon={<IconChevronDown />}
                onClick={() => navigateToSection('down')}
                style={{
                  borderRadius: '50%',
                  width: '32px',
                  height: '32px',
                  padding: 0,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}
                title={t('下一个表单块')}
              />
            </div>
            <Space>
              <Button
                theme='solid'
                onClick={() => formApiRef.current?.submitForm()}
                icon={<IconSave />}
              >
                {t('提交')}
              </Button>
              <Button
                theme='light'
                type='primary'
                onClick={handleCancel}
                icon={<IconClose />}
              >
                {t('取消')}
              </Button>
            </Space>
          </div>
        }
        closeIcon={null}
        onCancel={() => handleCancel()}
      >
        <Form
          key={isEdit ? 'edit' : 'new'}
          initValues={originInputs}
          getFormApi={(api) => (formApiRef.current = api)}
          onSubmit={submit}
        >
          {() => (
            <Spin spinning={loading}>
              <div className='p-2' ref={formContainerRef}>
                <div ref={(el) => (formSectionRefs.current.basicInfo = el)}>
                  <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
                    {/* Header: Basic Info */}
                    <div className='flex items-center mb-2'>
                      <Avatar
                        size='small'
                        color='blue'
                        className='mr-2 shadow-md'
                      >
                        <IconServer size={16} />
                      </Avatar>
                      <div>
                        <Text className='text-lg font-medium'>
                          {t('基本信息')}
                        </Text>
                        <div className='text-xs text-gray-600'>
                          {t('渠道的基本配置信息')}
                        </div>
                      </div>
                    </div>

                    <Form.Select
                      field='type'
                      label={t('类型')}
                      placeholder={t('请选择渠道类型')}
                      rules={[{ required: true, message: t('请选择渠道类型') }]}
                      optionList={channelOptionList}
                      style={{ width: '100%' }}
                      filter={selectFilter}
                      autoClearSearchValue={false}
                      searchPosition='dropdown'
                      onSearch={(value) => setChannelSearchValue(value)}
                      renderOptionItem={renderChannelOption}
                      onChange={(value) => handleInputChange('type', value)}
                    />

                    {inputs.type === 20 && (
                      <Form.Switch
                        field='is_enterprise_account'
                        label={t('是否为企业账户')}
                        checkedText={t('')}
                        uncheckedText={t('')}
                        onChange={(value) => {
                          setIsEnterpriseAccount(value);
                          handleInputChange('is_enterprise_account', value);
                        }}
                        extraText={t(
                          '企业账户为特殊返回格式,需要特殊处理,如果非企业账户,请勿勾选',
                        )}
                        initValue={inputs.is_enterprise_account}
                      />
                    )}

                    <Form.Input
                      field='name'
                      label={t('名称')}
                      placeholder={t('请为渠道命名')}
                      rules={[{ required: true, message: t('请为渠道命名') }]}
                      showClear
                      onChange={(value) => handleInputChange('name', value)}
                      autoComplete='new-password'
                    />

                    {inputs.type === 33 && (
                      <>
                        <Form.Select
                          field='aws_key_type'
                          label={t('密钥格式')}
                          placeholder={t('请选择密钥格式')}
                          optionList={[
                            {
                              label: 'AccessKey / SecretAccessKey',
                              value: 'ak_sk',
                            },
                            { label: 'API Key', value: 'api_key' },
                          ]}
                          style={{ width: '100%' }}
                          value={inputs.aws_key_type || 'ak_sk'}
                          onChange={(value) => {
                            handleChannelOtherSettingsChange('aws_key_type', value);
                          }}
                          extraText={t(
                            'AK/SK 模式:使用 AccessKey 和 SecretAccessKey;API Key 模式:使用 API Key',
                          )}
                        />
                      </>
                    )}

                    {inputs.type === 41 && (
                      <Form.Select
                        field='vertex_key_type'
                        label={t('密钥格式')}
                        placeholder={t('请选择密钥格式')}
                        optionList={[
                          { label: 'JSON', value: 'json' },
                          { label: 'API Key', value: 'api_key' },
                        ]}
                        style={{ width: '100%' }}
                        value={inputs.vertex_key_type || 'json'}
                        onChange={(value) => {
                          // 更新设置中的 vertex_key_type
                          handleChannelOtherSettingsChange(
                            'vertex_key_type',
                            value,
                          );
                          // 切换为 api_key 时,关闭批量与手动/文件切换,并清理已选文件
                          if (value === 'api_key') {
                            setBatch(false);
                            setUseManualInput(false);
                            setVertexKeys([]);
                            setVertexFileList([]);
                            if (formApiRef.current) {
                              formApiRef.current.setValue('vertex_files', []);
                            }
                          }
                        }}
                        extraText={
                          inputs.vertex_key_type === 'api_key'
                            ? t('API Key 模式下不支持批量创建')
                            : t('JSON 模式支持手动输入或上传服务账号 JSON')
                        }
                      />
                    )}
                    {batch ? (
                      inputs.type === 41 &&
                      (inputs.vertex_key_type || 'json') === 'json' ? (
                        <Form.Upload
                          field='vertex_files'
                          label={t('密钥文件 (.json)')}
                          accept='.json'
                          multiple
                          draggable
                          dragIcon={<IconBolt />}
                          dragMainText={t('点击上传文件或拖拽文件到这里')}
                          dragSubText={t('仅支持 JSON 文件,支持多文件')}
                          style={{ marginTop: 10 }}
                          uploadTrigger='custom'
                          beforeUpload={() => false}
                          onChange={handleVertexUploadChange}
                          fileList={vertexFileList}
                          rules={
                            isEdit
                              ? []
                              : [
                                  {
                                    required: true,
                                    message: t('请上传密钥文件'),
                                  },
                                ]
                          }
                          extraText={batchExtra}
                        />
                      ) : (
                        <Form.TextArea
                          field='key'
                          label={t('密钥')}
                          placeholder={
                            inputs.type === 33
                              ? inputs.aws_key_type === 'api_key'
                                ? t('请输入 API Key一行一个格式APIKey|Region')
                                : t(
                                    '请输入密钥一行一个格式AccessKey|SecretAccessKey|Region',
                                  )
                              : t('请输入密钥一行一个')
                          }
                          rules={
                            isEdit
                              ? []
                              : [{ required: true, message: t('请输入密钥') }]
                          }
                          autosize
                          autoComplete='new-password'
                          onChange={(value) => handleInputChange('key', value)}
                          extraText={
                            <div className='flex items-center gap-2 flex-wrap'>
                              {isEdit &&
                                isMultiKeyChannel &&
                                keyMode === 'append' && (
                                  <Text type='warning' size='small'>
                                    {t(
                                      '追加模式:新密钥将添加到现有密钥列表的末尾',
                                    )}
                                  </Text>
                                )}
                              {isEdit && (
                                <Button
                                  size='small'
                                  type='primary'
                                  theme='outline'
                                  onClick={handleShow2FAModal}
                                >
                                  {t('查看密钥')}
                                </Button>
                              )}
                              {batchExtra}
                            </div>
                          }
                          showClear
                        />
                      )
                    ) : (
                      <>
                        {inputs.type === 41 &&
                        (inputs.vertex_key_type || 'json') === 'json' ? (
                          <>
                            {!batch && (
                              <div className='flex items-center justify-between mb-3'>
                                <Text className='text-sm font-medium'>
                                  {t('密钥输入方式')}
                                </Text>
                                <Space>
                                  <Button
                                    size='small'
                                    type={
                                      !useManualInput ? 'primary' : 'tertiary'
                                    }
                                    onClick={() => {
                                      setUseManualInput(false);
                                      // 切换到文件上传模式时清空手动输入的密钥
                                      if (formApiRef.current) {
                                        formApiRef.current.setValue('key', '');
                                      }
                                      handleInputChange('key', '');
                                    }}
                                  >
                                    {t('文件上传')}
                                  </Button>
                                  <Button
                                    size='small'
                                    type={
                                      useManualInput ? 'primary' : 'tertiary'
                                    }
                                    onClick={() => {
                                      setUseManualInput(true);
                                      // 切换到手动输入模式时清空文件上传相关状态
                                      setVertexKeys([]);
                                      setVertexFileList([]);
                                      if (formApiRef.current) {
                                        formApiRef.current.setValue(
                                          'vertex_files',
                                          [],
                                        );
                                      }
                                      setInputs((prev) => ({
                                        ...prev,
                                        vertex_files: [],
                                      }));
                                    }}
                                  >
                                    {t('手动输入')}
                                  </Button>
                                </Space>
                              </div>
                            )}

                            {batch && (
                              <Banner
                                type='info'
                                description={t(
                                  '批量创建模式下仅支持文件上传不支持手动输入',
                                )}
                                className='!rounded-lg mb-3'
                              />
                            )}

                            {useManualInput && !batch ? (
                              <Form.TextArea
                                field='key'
                                label={
                                  isEdit
                                    ? t(
                                        '密钥编辑模式下保存的密钥不会显示)',
                                      )
                                    : t('密钥')
                                }
                                placeholder={t(
                                  '请输入 JSON 格式的密钥内容例如:\n{\n  "type": "service_account",\n  "project_id": "your-project-id",\n  "private_key_id": "...",\n  "private_key": "...",\n  "client_email": "...",\n  "client_id": "...",\n  "auth_uri": "...",\n  "token_uri": "...",\n  "auth_provider_x509_cert_url": "...",\n  "client_x509_cert_url": "..."\n}',
                                )}
                                rules={
                                  isEdit
                                    ? []
                                    : [
                                        {
                                          required: true,
                                          message: t('请输入密钥'),
                                        },
                                      ]
                                }
                                autoComplete='new-password'
                                onChange={(value) =>
                                  handleInputChange('key', value)
                                }
                                extraText={
                                  <div className='flex items-center gap-2'>
                                    <Text type='tertiary' size='small'>
                                      {t('请输入完整的 JSON 格式密钥内容')}
                                    </Text>
                                    {isEdit &&
                                      isMultiKeyChannel &&
                                      keyMode === 'append' && (
                                        <Text type='warning' size='small'>
                                          {t(
                                            '追加模式:新密钥将添加到现有密钥列表的末尾',
                                          )}
                                        </Text>
                                      )}
                                    {isEdit && (
                                      <Button
                                        size='small'
                                        type='primary'
                                        theme='outline'
                                        onClick={handleShow2FAModal}
                                      >
                                        {t('查看密钥')}
                                      </Button>
                                    )}
                                    {batchExtra}
                                  </div>
                                }
                                autosize
                                showClear
                              />
                            ) : (
                              <Form.Upload
                                field='vertex_files'
                                label={t('密钥文件 (.json)')}
                                accept='.json'
                                draggable
                                dragIcon={<IconBolt />}
                                dragMainText={t('点击上传文件或拖拽文件到这里')}
                                dragSubText={t('仅支持 JSON 文件')}
                                style={{ marginTop: 10 }}
                                uploadTrigger='custom'
                                beforeUpload={() => false}
                                onChange={handleVertexUploadChange}
                                fileList={vertexFileList}
                                rules={
                                  isEdit
                                    ? []
                                    : [
                                        {
                                          required: true,
                                          message: t('请上传密钥文件'),
                                        },
                                      ]
                                }
                                extraText={batchExtra}
                              />
                            )}
                          </>
                        ) : (
                          <Form.Input
                            field='key'
                            label={
                              isEdit
                                ? t('密钥编辑模式下保存的密钥不会显示)')
                                : t('密钥')
                            }
                            placeholder={
                              inputs.type === 33
                                ? inputs.aws_key_type === 'api_key'
                                  ? t('请输入 API Key格式APIKey|Region')
                                  : t('按照如下格式输入AccessKey|SecretAccessKey|Region')
                                : t(type2secretPrompt(inputs.type))
                            }
                            rules={
                              isEdit
                                ? []
                                : [{ required: true, message: t('请输入密钥') }]
                            }
                            autoComplete='new-password'
                            onChange={(value) =>
                              handleInputChange('key', value)
                            }
                            extraText={
                              <div className='flex items-center gap-2'>
                                {isEdit &&
                                  isMultiKeyChannel &&
                                  keyMode === 'append' && (
                                    <Text type='warning' size='small'>
                                      {t(
                                        '追加模式:新密钥将添加到现有密钥列表的末尾',
                                      )}
                                    </Text>
                                  )}
                                {isEdit && (
                                  <Button
                                    size='small'
                                    type='primary'
                                    theme='outline'
                                    onClick={handleShow2FAModal}
                                  >
                                    {t('查看密钥')}
                                  </Button>
                                )}
                                {batchExtra}
                              </div>
                            }
                            showClear
                          />
                        )}
                      </>
                    )}

                    {isEdit && isMultiKeyChannel && (
                      <Form.Select
                        field='key_mode'
                        label={t('密钥更新模式')}
                        placeholder={t('请选择密钥更新模式')}
                        optionList={[
                          { label: t('追加到现有密钥'), value: 'append' },
                          { label: t('覆盖现有密钥'), value: 'replace' },
                        ]}
                        style={{ width: '100%' }}
                        value={keyMode}
                        onChange={(value) => setKeyMode(value)}
                        extraText={
                          <Text type='tertiary' size='small'>
                            {keyMode === 'replace'
                              ? t('覆盖模式:将完全替换现有的所有密钥')
                              : t('追加模式:将新密钥添加到现有密钥列表末尾')}
                          </Text>
                        }
                      />
                    )}
                    {batch && multiToSingle && (
                      <>
                        <Form.Select
                          field='multi_key_mode'
                          label={t('密钥聚合模式')}
                          placeholder={t('请选择多密钥使用策略')}
                          optionList={[
                            { label: t('随机'), value: 'random' },
                            { label: t('轮询'), value: 'polling' },
                          ]}
                          style={{ width: '100%' }}
                          value={inputs.multi_key_mode || 'random'}
                          onChange={(value) => {
                            setMultiKeyMode(value);
                            handleInputChange('multi_key_mode', value);
                          }}
                        />
                        {inputs.multi_key_mode === 'polling' && (
                          <Banner
                            type='warning'
                            description={t(
                              '轮询模式必须搭配Redis和内存缓存功能使用否则性能将大幅降低并且无法实现轮询功能',
                            )}
                            className='!rounded-lg mt-2'
                          />
                        )}
                      </>
                    )}

                    {inputs.type === 18 && (
                      <Form.Input
                        field='other'
                        label={t('模型版本')}
                        placeholder={
                          '请输入星火大模型版本注意是接口地址中的版本号例如v2.1'
                        }
                        onChange={(value) => handleInputChange('other', value)}
                        showClear
                      />
                    )}

                    {inputs.type === 41 && (
                      <JSONEditor
                        key={`region-${isEdit ? channelId : 'new'}`}
                        field='other'
                        label={t('部署地区')}
                        placeholder={t(
                          '请输入部署地区例如us-central1\n支持使用模型映射格式\n{\n    "default": "us-central1",\n    "claude-3-5-sonnet-20240620": "europe-west1"\n}',
                        )}
                        value={inputs.other || ''}
                        onChange={(value) => handleInputChange('other', value)}
                        rules={[
                          { required: true, message: t('请填写部署地区') },
                        ]}
                        template={REGION_EXAMPLE}
                        templateLabel={t('填入模板')}
                        editorType='region'
                        formApi={formApiRef.current}
                        extraText={t('设置默认地区和特定模型的专用地区')}
                      />
                    )}

                    {inputs.type === 21 && (
                      <Form.Input
                        field='other'
                        label={t('知识库 ID')}
                        placeholder={'请输入知识库 ID例如123456'}
                        onChange={(value) => handleInputChange('other', value)}
                        showClear
                      />
                    )}

                    {inputs.type === 39 && (
                      <Form.Input
                        field='other'
                        label='Account ID'
                        placeholder={
                          '请输入Account ID例如d6b5da8hk1awo8nap34ube6gh'
                        }
                        onChange={(value) => handleInputChange('other', value)}
                        showClear
                      />
                    )}

                    {inputs.type === 49 && (
                      <Form.Input
                        field='other'
                        label={t('智能体ID')}
                        placeholder={'请输入智能体ID例如7342866812345'}
                        onChange={(value) => handleInputChange('other', value)}
                        showClear
                      />
                    )}

                    {inputs.type === 1 && (
                      <Form.Input
                        field='openai_organization'
                        label={t('组织')}
                        placeholder={t('请输入组织org-xxx')}
                        showClear
                        helpText={t('组织不填则为默认组织')}
                        onChange={(value) =>
                          handleInputChange('openai_organization', value)
                        }
                      />
                    )}
                  </Card>
                </div>

                {/* API Configuration Card */}
                {showApiConfigCard && (
                  <div ref={(el) => (formSectionRefs.current.apiConfig = el)}>
                    <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
                      {/* Header: API Config */}
                      <div
                        className='flex items-center mb-2'
                        onClick={handleApiConfigSecretClick}
                      >
                        <Avatar
                          size='small'
                          color='green'
                          className='mr-2 shadow-md'
                        >
                          <IconGlobe size={16} />
                        </Avatar>
                        <div>
                          <Text className='text-lg font-medium'>
                            {t('API 配置')}
                          </Text>
                          <div className='text-xs text-gray-600'>
                            {t('API 地址和相关配置')}
                          </div>
                        </div>
                      </div>

                      {inputs.type === 40 && (
                        <Banner
                          type='info'
                          description={
                            <div>
                              <Text strong>{t('邀请链接')}:</Text>
                              <Text
                                link
                                underline
                                className='ml-2 cursor-pointer'
                                onClick={() =>
                                  window.open(
                                    'https://cloud.siliconflow.cn/i/hij0YNTZ',
                                  )
                                }
                              >
                                https://cloud.siliconflow.cn/i/hij0YNTZ
                              </Text>
                            </div>
                          }
                          className='!rounded-lg'
                        />
                      )}

                      {inputs.type === 3 && (
                        <>
                          <Banner
                            type='warning'
                            description={t(
                              '2025年5月10日后添加的渠道不需要再在部署的时候移除模型名称中的"."',
                            )}
                            className='!rounded-lg'
                          />
                          <div>
                            <Form.Input
                              field='base_url'
                              label='AZURE_OPENAI_ENDPOINT'
                              placeholder={t(
                                '请输入 AZURE_OPENAI_ENDPOINT例如https://docs-test-001.openai.azure.com',
                              )}
                              onChange={(value) =>
                                handleInputChange('base_url', value)
                              }
                              showClear
                            />
                          </div>
                          <div>
                            <Form.Input
                              field='other'
                              label={t('默认 API 版本')}
                              placeholder={t(
                                '请输入默认 API 版本例如2025-04-01-preview',
                              )}
                              onChange={(value) =>
                                handleInputChange('other', value)
                              }
                              showClear
                            />
                          </div>
                          <div>
                            <Form.Input
                              field='azure_responses_version'
                              label={t(
                                '默认 Responses API 版本为空则使用上方版本',
                              )}
                              placeholder={t('例如preview')}
                              onChange={(value) =>
                                handleChannelOtherSettingsChange(
                                  'azure_responses_version',
                                  value,
                                )
                              }
                              showClear
                            />
                          </div>
                        </>
                      )}

                      {inputs.type === 8 && (
                        <>
                          <Banner
                            type='warning'
                            description={t(
                              '如果你对接的是上游One API或者New API等转发项目请使用OpenAI类型不要使用此类型除非你知道你在做什么。',
                            )}
                            className='!rounded-lg'
                          />
                          <div>
                            <Form.Input
                              field='base_url'
                              label={t('完整的 Base URL支持变量{model}')}
                              placeholder={t(
                                '请输入完整的URL例如https://api.openai.com/v1/chat/completions',
                              )}
                              onChange={(value) =>
                                handleInputChange('base_url', value)
                              }
                              showClear
                            />
                          </div>
                        </>
                      )}

                      {inputs.type === 37 && (
                        <Banner
                          type='warning'
                          description={t(
                            'Dify渠道只适配chatflow和agent并且agent不支持图片!',
                          )}
                          className='!rounded-lg'
                        />
                      )}

                      {inputs.type !== 3 &&
                        inputs.type !== 8 &&
                        inputs.type !== 22 &&
                        inputs.type !== 36 &&
                        (inputs.type !== 45 || doubaoApiEditUnlocked) && (
                          <div>
                            <Form.Input
                              field='base_url'
                              label={t('API地址')}
                              placeholder={t(
                                '此项可选用于通过自定义API地址来进行 API 调用末尾不要带/v1和/',
                              )}
                              onChange={(value) =>
                                handleInputChange('base_url', value)
                              }
                              showClear
                              extraText={t(
                                '对于官方渠道,new-api已经内置地址,除非是第三方代理站点或者Azure的特殊接入地址,否则不需要填写',
                              )}
                            />
                          </div>
                        )}

                      {inputs.type === 22 && (
                        <div>
                          <Form.Input
                            field='base_url'
                            label={t('私有部署地址')}
                            placeholder={t(
                              '请输入私有部署地址格式为https://fastgpt.run/api/openapi',
                            )}
                            onChange={(value) =>
                              handleInputChange('base_url', value)
                            }
                            showClear
                          />
                        </div>
                      )}

                      {inputs.type === 36 && (
                        <div>
                          <Form.Input
                            field='base_url'
                            label={t(
                              '注意非Chat API请务必填写正确的API地址否则可能导致无法使用',
                            )}
                            placeholder={t(
                              '请输入到 /suno 前的路径通常就是域名例如https://api.example.com',
                            )}
                            onChange={(value) =>
                              handleInputChange('base_url', value)
                            }
                            showClear
                          />
                        </div>
                      )}

                      {inputs.type === 45 && !doubaoApiEditUnlocked && (
                        <div>
                          <Form.Select
                            field='base_url'
                            label={t('API地址')}
                            placeholder={t('请选择API地址')}
                            onChange={(value) =>
                              handleInputChange('base_url', value)
                            }
                            optionList={[
                              {
                                value: 'https://ark.cn-beijing.volces.com',
                                label: 'https://ark.cn-beijing.volces.com',
                              },
                              {
                                value:
                                  'https://ark.ap-southeast.bytepluses.com',
                                label:
                                  'https://ark.ap-southeast.bytepluses.com',
                              },
                                {
                                    value: 'doubao-coding-plan',
                                    label: 'Doubao Coding Plan',
                                },
                            ]}
                            defaultValue='https://ark.cn-beijing.volces.com'
                          />
                        </div>
                      )}
                    </Card>
                  </div>
                )}

                {/* Model Configuration Card */}
                <div ref={(el) => (formSectionRefs.current.modelConfig = el)}>
                  <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
                    {/* Header: Model Config */}
                    <div className='flex items-center mb-2'>
                      <Avatar
                        size='small'
                        color='purple'
                        className='mr-2 shadow-md'
                      >
                        <IconCode size={16} />
                      </Avatar>
                      <div>
                        <Text className='text-lg font-medium'>
                          {t('模型配置')}
                        </Text>
                        <div className='text-xs text-gray-600'>
                          {t('模型选择和映射设置')}
                        </div>
                      </div>
                    </div>

                    <Form.Select
                      field='models'
                      label={t('模型')}
                      placeholder={t('请选择该渠道所支持的模型')}
                      rules={[{ required: true, message: t('请选择模型') }]}
                      multiple
                      filter={selectFilter}
                      autoClearSearchValue={false}
                      searchPosition='dropdown'
                      optionList={modelOptions}
                      style={{ width: '100%' }}
                      onChange={(value) => handleInputChange('models', value)}
                      renderSelectedItem={(optionNode) => {
                        const modelName = String(optionNode?.value ?? '');
                        return {
                          isRenderInTag: true,
                          content: (
                            <span
                              className='cursor-pointer select-none'
                              role='button'
                              tabIndex={0}
                              title={t('点击复制模型名称')}
                              onClick={async (e) => {
                                e.stopPropagation();
                                const ok = await copy(modelName);
                                if (ok) {
                                  showSuccess(
                                    t('已复制:{{name}}', { name: modelName }),
                                  );
                                } else {
                                  showError(t('复制失败'));
                                }
                              }}
                            >
                              {optionNode.label || modelName}
                            </span>
                          ),
                        };
                      }}
                      extraText={
                        <Space wrap>
                          <Button
                            size='small'
                            type='primary'
                            onClick={() =>
                              handleInputChange('models', basicModels)
                            }
                          >
                            {t('填入相关模型')}
                          </Button>
                          <Button
                            size='small'
                            type='secondary'
                            onClick={() =>
                              handleInputChange('models', fullModels)
                            }
                          >
                            {t('填入所有模型')}
                          </Button>
                          {MODEL_FETCHABLE_TYPES.has(inputs.type) && (
                            <Button
                              size='small'
                              type='tertiary'
                              onClick={() => fetchUpstreamModelList('models')}
                            >
                              {t('获取模型列表')}
                            </Button>
                          )}
                          <Button
                            size='small'
                            type='warning'
                            onClick={() => handleInputChange('models', [])}
                          >
                            {t('清除所有模型')}
                          </Button>
                          <Button
                            size='small'
                            type='tertiary'
                            onClick={() => {
                              if (inputs.models.length === 0) {
                                showInfo(t('没有模型可以复制'));
                                return;
                              }
                              try {
                                copy(inputs.models.join(','));
                                showSuccess(t('模型列表已复制到剪贴板'));
                              } catch (error) {
                                showError(t('复制失败'));
                              }
                            }}
                          >
                            {t('复制所有模型')}
                          </Button>
                          {modelGroups &&
                            modelGroups.length > 0 &&
                            modelGroups.map((group) => (
                              <Button
                                key={group.id}
                                size='small'
                                type='primary'
                                onClick={() => {
                                  let items = [];
                                  try {
                                    if (Array.isArray(group.items)) {
                                      items = group.items;
                                    } else if (
                                      typeof group.items === 'string'
                                    ) {
                                      const parsed = JSON.parse(
                                        group.items || '[]',
                                      );
                                      if (Array.isArray(parsed)) items = parsed;
                                    }
                                  } catch {}
                                  const current =
                                    formApiRef.current?.getValue('models') ||
                                    inputs.models ||
                                    [];
                                  const merged = Array.from(
                                    new Set(
                                      [...current, ...items]
                                        .map((m) => (m || '').trim())
                                        .filter(Boolean),
                                    ),
                                  );
                                  handleInputChange('models', merged);
                                }}
                              >
                                {group.name}
                              </Button>
                            ))}
                        </Space>
                      }
                    />

                    <Form.Input
                      field='custom_model'
                      label={t('自定义模型名称')}
                      placeholder={t('输入自定义模型名称')}
                      onChange={(value) => setCustomModel(value.trim())}
                      value={customModel}
                      suffix={
                        <Button
                          size='small'
                          type='primary'
                          onClick={addCustomModels}
                        >
                          {t('填入')}
                        </Button>
                      }
                    />

                    <Form.Input
                      field='test_model'
                      label={t('默认测试模型')}
                      placeholder={t('不填则为模型列表第一个')}
                      onChange={(value) =>
                        handleInputChange('test_model', value)
                      }
                      showClear
                    />

                    <JSONEditor
                      key={`model_mapping-${isEdit ? channelId : 'new'}`}
                      field='model_mapping'
                      label={t('模型重定向')}
                      placeholder={
                        t(
                          '此项可选用于修改请求体中的模型名称为一个 JSON 字符串键为请求中模型名称值为要替换的模型名称例如:',
                        ) +
                        `\n${JSON.stringify(MODEL_MAPPING_EXAMPLE, null, 2)}`
                      }
                      value={inputs.model_mapping || ''}
                      onChange={(value) =>
                        handleInputChange('model_mapping', value)
                      }
                      template={MODEL_MAPPING_EXAMPLE}
                      templateLabel={t('填入模板')}
                      editorType='keyValue'
                      formApi={formApiRef.current}
                      extraText={t(
                        '键为请求中的模型名称,值为要替换的模型名称',
                      )}
                    />
                  </Card>
                </div>

                {/* Advanced Settings Card */}
                <div
                  ref={(el) => (formSectionRefs.current.advancedSettings = el)}
                >
                  <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
                    {/* Header: Advanced Settings */}
                    <div className='flex items-center mb-2'>
                      <Avatar
                        size='small'
                        color='orange'
                        className='mr-2 shadow-md'
                      >
                        <IconSetting size={16} />
                      </Avatar>
                      <div>
                        <Text className='text-lg font-medium'>
                          {t('高级设置')}
                        </Text>
                        <div className='text-xs text-gray-600'>
                          {t('渠道的高级配置选项')}
                        </div>
                      </div>
                    </div>

                    <Form.Select
                      field='groups'
                      label={t('分组')}
                      placeholder={t('请选择可以使用该渠道的分组')}
                      multiple
                      allowAdditions
                      additionLabel={t(
                        '请在系统设置页面编辑分组倍率以添加新的分组:',
                      )}
                      optionList={groupOptions}
                      style={{ width: '100%' }}
                      onChange={(value) => handleInputChange('groups', value)}
                    />

                    <Form.Input
                      field='tag'
                      label={t('渠道标签')}
                      placeholder={t('渠道标签')}
                      showClear
                      onChange={(value) => handleInputChange('tag', value)}
                    />
                    <Form.TextArea
                      field='remark'
                      label={t('备注')}
                      placeholder={t('请输入备注仅管理员可见)')}
                      maxLength={255}
                      showClear
                      onChange={(value) => handleInputChange('remark', value)}
                    />

                    <Row gutter={12}>
                      <Col span={12}>
                        <Form.InputNumber
                          field='priority'
                          label={t('渠道优先级')}
                          placeholder={t('渠道优先级')}
                          min={0}
                          onNumberChange={(value) =>
                            handleInputChange('priority', value)
                          }
                          style={{ width: '100%' }}
                        />
                      </Col>
                      <Col span={12}>
                        <Form.InputNumber
                          field='weight'
                          label={t('渠道权重')}
                          placeholder={t('渠道权重')}
                          min={0}
                          onNumberChange={(value) =>
                            handleInputChange('weight', value)
                          }
                          style={{ width: '100%' }}
                        />
                      </Col>
                    </Row>

                    <Form.Switch
                      field='auto_ban'
                      label={t('是否自动禁用')}
                      checkedText={t('')}
                      uncheckedText={t('')}
                      onChange={(value) => setAutoBan(value)}
                      extraText={t(
                        '仅当自动禁用开启时有效,关闭后不会自动禁用该渠道',
                      )}
                      initValue={autoBan}
                    />

                    <Form.TextArea
                      field='param_override'
                      label={t('参数覆盖')}
                      placeholder={
                        t(
                          '此项可选用于覆盖请求参数不支持覆盖 stream 参数',
                        ) +
                        '\n' +
                        t('旧格式直接覆盖):') +
                        '\n{\n  "temperature": 0,\n  "max_tokens": 1000\n}' +
                        '\n\n' +
                        t('新格式支持条件判断与json自定义):') +
                        '\n{\n  "operations": [\n    {\n      "path": "temperature",\n      "mode": "set",\n      "value": 0.7,\n      "conditions": [\n        {\n          "path": "model",\n          "mode": "prefix",\n          "value": "gpt"\n        }\n      ]\n    }\n  ]\n}'
                      }
                      autosize
                      onChange={(value) =>
                        handleInputChange('param_override', value)
                      }
                      extraText={
                        <div className='flex gap-2 flex-wrap'>
                          <Text
                            className='!text-semi-color-primary cursor-pointer'
                            onClick={() =>
                              handleInputChange(
                                'param_override',
                                JSON.stringify({ temperature: 0 }, null, 2),
                              )
                            }
                          >
                            {t('旧格式模板')}
                          </Text>
                          <Text
                            className='!text-semi-color-primary cursor-pointer'
                            onClick={() =>
                              handleInputChange(
                                'param_override',
                                JSON.stringify(
                                  {
                                    operations: [
                                      {
                                        path: 'temperature',
                                        mode: 'set',
                                        value: 0.7,
                                        conditions: [
                                          {
                                            path: 'model',
                                            mode: 'prefix',
                                            value: 'gpt',
                                          },
                                        ],
                                        logic: 'AND',
                                      },
                                    ],
                                  },
                                  null,
                                  2,
                                ),
                              )
                            }
                          >
                            {t('新格式模板')}
                          </Text>
                        </div>
                      }
                      showClear
                    />

                    <Form.TextArea
                      field='header_override'
                      label={t('请求头覆盖')}
                      placeholder={
                        t('此项可选用于覆盖请求头参数') +
                        '\n' +
                        t('格式示例:') +
                        '\n{\n  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0",\n  "Authorization": "Bearer {api_key}"\n}'
                      }
                      autosize
                      onChange={(value) =>
                        handleInputChange('header_override', value)
                      }
                      extraText={
                        <div className='flex flex-col gap-1'>
                          <div className='flex gap-2 flex-wrap items-center'>
                            <Text
                              className='!text-semi-color-primary cursor-pointer'
                              onClick={() =>
                                handleInputChange(
                                  'header_override',
                                  JSON.stringify(
                                    {
                                      'User-Agent':
                                        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0',
                                      Authorization: 'Bearer{api_key}',
                                    },
                                    null,
                                    2,
                                  ),
                                )
                              }
                            >
                              {t('填入模板')}
                            </Text>
                          </div>
                          <div>
                            <Text type='tertiary' size='small'>
                              {t('支持变量:')}
                            </Text>
                            <div className='text-xs text-tertiary ml-2'>
                              <div>
                                {t('渠道密钥')}: {'{api_key}'}
                              </div>
                            </div>
                          </div>
                        </div>
                      }
                      showClear
                    />

                    <JSONEditor
                      key={`status_code_mapping-${isEdit ? channelId : 'new'}`}
                      field='status_code_mapping'
                      label={t('状态码复写')}
                      placeholder={
                        t(
                          '此项可选用于复写返回的状态码仅影响本地判断不修改返回到上游的状态码比如将claude渠道的400错误复写为500用于重试),请勿滥用该功能例如:',
                        ) +
                        '\n' +
                        JSON.stringify(STATUS_CODE_MAPPING_EXAMPLE, null, 2)
                      }
                      value={inputs.status_code_mapping || ''}
                      onChange={(value) =>
                        handleInputChange('status_code_mapping', value)
                      }
                      template={STATUS_CODE_MAPPING_EXAMPLE}
                      templateLabel={t('填入模板')}
                      editorType='keyValue'
                      formApi={formApiRef.current}
                      extraText={t(
                        '键为原状态码,值为要复写的状态码,仅影响本地判断',
                      )}
                    />

                    {/* 字段透传控制 - OpenAI 渠道 */}
                    {inputs.type === 1 && (
                      <>
                        <div className='mt-4 mb-2 text-sm font-medium text-gray-700'>
                          {t('字段透传控制')}
                        </div>

                        <Form.Switch
                          field='allow_service_tier'
                          label={t('允许 service_tier 透传')}
                          checkedText={t('')}
                          uncheckedText={t('')}
                          onChange={(value) =>
                            handleChannelOtherSettingsChange(
                              'allow_service_tier',
                              value,
                            )
                          }
                          extraText={t(
                            'service_tier 字段用于指定服务层级,允许透传可能导致实际计费高于预期。默认关闭以避免额外费用',
                          )}
                        />

                        <Form.Switch
                          field='disable_store'
                          label={t('禁用 store 透传')}
                          checkedText={t('')}
                          uncheckedText={t('')}
                          onChange={(value) =>
                            handleChannelOtherSettingsChange(
                              'disable_store',
                              value,
                            )
                          }
                          extraText={t(
                            'store 字段用于授权 OpenAI 存储请求数据以评估和优化产品。默认关闭,开启后可能导致 Codex 无法正常使用',
                          )}
                        />

                        <Form.Switch
                          field='allow_safety_identifier'
                          label={t('允许 safety_identifier 透传')}
                          checkedText={t('')}
                          uncheckedText={t('')}
                          onChange={(value) =>
                            handleChannelOtherSettingsChange(
                              'allow_safety_identifier',
                              value,
                            )
                          }
                          extraText={t(
                            'safety_identifier 字段用于帮助 OpenAI 识别可能违反使用政策的应用程序用户。默认关闭以保护用户隐私',
                          )}
                        />
                      </>
                    )}

                    {/* 字段透传控制 - Claude 渠道 */}
                    {inputs.type === 14 && (
                      <>
                        <div className='mt-4 mb-2 text-sm font-medium text-gray-700'>
                          {t('字段透传控制')}
                        </div>

                        <Form.Switch
                          field='allow_service_tier'
                          label={t('允许 service_tier 透传')}
                          checkedText={t('')}
                          uncheckedText={t('')}
                          onChange={(value) =>
                            handleChannelOtherSettingsChange(
                              'allow_service_tier',
                              value,
                            )
                          }
                          extraText={t(
                            'service_tier 字段用于指定服务层级,允许透传可能导致实际计费高于预期。默认关闭以避免额外费用',
                          )}
                        />
                      </>
                    )}
                  </Card>
                </div>

                {/* Channel Extra Settings Card */}
                <div
                  ref={(el) =>
                    (formSectionRefs.current.channelExtraSettings = el)
                  }
                >
                  <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
                    {/* Header: Channel Extra Settings */}
                    <div className='flex items-center mb-2'>
                      <Avatar
                        size='small'
                        color='violet'
                        className='mr-2 shadow-md'
                      >
                        <IconBolt size={16} />
                      </Avatar>
                      <div>
                        <Text className='text-lg font-medium'>
                          {t('渠道额外设置')}
                        </Text>
                      </div>
                    </div>

                    {inputs.type === 1 && (
                      <Form.Switch
                        field='force_format'
                        label={t('强制格式化')}
                        checkedText={t('')}
                        uncheckedText={t('')}
                        onChange={(value) =>
                          handleChannelSettingsChange('force_format', value)
                        }
                        extraText={t(
                          '强制将响应格式化为 OpenAI 标准格式(只适用于OpenAI渠道类型)',
                        )}
                      />
                    )}

                    <Form.Switch
                      field='thinking_to_content'
                      label={t('思考内容转换')}
                      checkedText={t('')}
                      uncheckedText={t('')}
                      onChange={(value) =>
                        handleChannelSettingsChange(
                          'thinking_to_content',
                          value,
                        )
                      }
                      extraText={t(
                        '将 reasoning_content 转换为 <think> 标签拼接到内容中',
                      )}
                    />

                    <Form.Switch
                      field='pass_through_body_enabled'
                      label={t('透传请求体')}
                      checkedText={t('')}
                      uncheckedText={t('')}
                      onChange={(value) =>
                        handleChannelSettingsChange(
                          'pass_through_body_enabled',
                          value,
                        )
                      }
                      extraText={t('启用请求体透传功能')}
                    />

                    <Form.Input
                      field='proxy'
                      label={t('代理地址')}
                      placeholder={t('例如: socks5://user:pass@host:port')}
                      onChange={(value) =>
                        handleChannelSettingsChange('proxy', value)
                      }
                      showClear
                      extraText={t('用于配置网络代理,支持 socks5 协议')}
                    />

                    <Form.TextArea
                      field='system_prompt'
                      label={t('系统提示词')}
                      placeholder={t(
                        '输入系统提示词用户的系统提示词将优先于此设置',
                      )}
                      onChange={(value) =>
                        handleChannelSettingsChange('system_prompt', value)
                      }
                      autosize
                      showClear
                      extraText={t(
                        '用户优先:如果用户在请求中指定了系统提示词,将优先使用用户的设置',
                      )}
                    />
                    <Form.Switch
                      field='system_prompt_override'
                      label={t('系统提示词拼接')}
                      checkedText={t('')}
                      uncheckedText={t('')}
                      onChange={(value) =>
                        handleChannelSettingsChange(
                          'system_prompt_override',
                          value,
                        )
                      }
                      extraText={t(
                        '如果用户请求中包含系统提示词,则使用此设置拼接到用户的系统提示词前面',
                      )}
                    />
                  </Card>
                </div>
              </div>
            </Spin>
          )}
        </Form>
        <ImagePreview
          src={modalImageUrl}
          visible={isModalOpenurl}
          onVisibleChange={(visible) => setIsModalOpenurl(visible)}
        />
      </SideSheet>
      {/* 使用通用安全验证模态框 */}
      <SecureVerificationModal
        visible={isModalVisible}
        verificationMethods={verificationMethods}
        verificationState={verificationState}
        onVerify={executeVerification}
        onCancel={cancelVerification}
        onCodeChange={setVerificationCode}
        onMethodSwitch={switchVerificationMethod}
        title={verificationState.title}
        description={verificationState.description}
      />

      {/* 使用ChannelKeyDisplay组件显示密钥 */}
      <Modal
        title={
          <div className='flex items-center'>
            <div className='w-8 h-8 rounded-full bg-green-100 dark:bg-green-900 flex items-center justify-center mr-3'>
              <svg
                className='w-4 h-4 text-green-600 dark:text-green-400'
                fill='currentColor'
                viewBox='0 0 20 20'
              >
                <path
                  fillRule='evenodd'
                  d='M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z'
                  clipRule='evenodd'
                />
              </svg>
            </div>
            {t('渠道密钥信息')}
          </div>
        }
        visible={keyDisplayState.showModal}
        onCancel={resetKeyDisplayState}
        footer={
          <Button type='primary' onClick={resetKeyDisplayState}>
            {t('完成')}
          </Button>
        }
        width={700}
        style={{ maxWidth: '90vw' }}
      >
        <ChannelKeyDisplay
          keyData={keyDisplayState.keyData}
          showSuccessIcon={true}
          successText={t('密钥获取成功')}
          showWarning={true}
          warningText={t(
            '请妥善保管密钥信息不要泄露给他人如有安全疑虑请及时更换密钥。',
          )}
        />
      </Modal>

      <ModelSelectModal
        visible={modelModalVisible}
        models={fetchedModels}
        selected={inputs.models}
        redirectModels={redirectModelList}
        onConfirm={(selectedModels) => {
          handleInputChange('models', selectedModels);
          showSuccess(t('模型列表已更新'));
          setModelModalVisible(false);
        }}
        onCancel={() => setModelModalVisible(false)}
      />
    </>
  );
};

export default EditChannelModal;