ChannelsTable.js 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872
  1. import React, { useEffect, useState } from 'react';
  2. import {
  3. API,
  4. showError,
  5. showInfo,
  6. showSuccess,
  7. timestamp2string,
  8. renderGroup,
  9. renderNumberWithPoint,
  10. renderQuota
  11. } from '../../helpers/index.js';
  12. import { CHANNEL_OPTIONS, ITEMS_PER_PAGE } from '../../constants/index.js';
  13. import {
  14. Button,
  15. Divider,
  16. Dropdown,
  17. Input,
  18. InputNumber,
  19. Modal,
  20. Space,
  21. SplitButtonGroup,
  22. Switch,
  23. Table,
  24. Tag,
  25. Tooltip,
  26. Typography,
  27. Checkbox,
  28. Card,
  29. Select
  30. } from '@douyinfe/semi-ui';
  31. import EditChannel from '../../pages/Channel/EditChannel.js';
  32. import {
  33. IconList,
  34. IconTreeTriangleDown,
  35. IconFilter,
  36. IconPlus,
  37. IconRefresh,
  38. IconSetting,
  39. IconSearch,
  40. IconEdit,
  41. IconDelete,
  42. IconStop,
  43. IconPlay,
  44. IconMore,
  45. IconCopy,
  46. IconSmallTriangleRight
  47. } from '@douyinfe/semi-icons';
  48. import { loadChannelModels } from '../../helpers/index.js';
  49. import EditTagModal from '../../pages/Channel/EditTagModal.js';
  50. import { useTranslation } from 'react-i18next';
  51. const ChannelsTable = () => {
  52. const { t } = useTranslation();
  53. let type2label = undefined;
  54. const renderType = (type) => {
  55. if (!type2label) {
  56. type2label = new Map();
  57. for (let i = 0; i < CHANNEL_OPTIONS.length; i++) {
  58. type2label[CHANNEL_OPTIONS[i].value] = CHANNEL_OPTIONS[i];
  59. }
  60. type2label[0] = { value: 0, label: t('未知类型'), color: 'grey' };
  61. }
  62. return (
  63. <Tag size='large' color={type2label[type]?.color} shape='circle'>
  64. {type2label[type]?.label}
  65. </Tag>
  66. );
  67. };
  68. const renderTagType = () => {
  69. return (
  70. <Tag
  71. color='light-blue'
  72. prefixIcon={<IconList />}
  73. size='large'
  74. shape='circle'
  75. type='light'
  76. >
  77. {t('标签聚合')}
  78. </Tag>
  79. );
  80. };
  81. const renderStatus = (status) => {
  82. switch (status) {
  83. case 1:
  84. return (
  85. <Tag size='large' color='green' shape='circle'>
  86. {t('已启用')}
  87. </Tag>
  88. );
  89. case 2:
  90. return (
  91. <Tag size='large' color='yellow' shape='circle'>
  92. {t('已禁用')}
  93. </Tag>
  94. );
  95. case 3:
  96. return (
  97. <Tag size='large' color='yellow' shape='circle'>
  98. {t('自动禁用')}
  99. </Tag>
  100. );
  101. default:
  102. return (
  103. <Tag size='large' color='grey' shape='circle'>
  104. {t('未知状态')}
  105. </Tag>
  106. );
  107. }
  108. };
  109. const renderResponseTime = (responseTime) => {
  110. let time = responseTime / 1000;
  111. time = time.toFixed(2) + t(' 秒');
  112. if (responseTime === 0) {
  113. return (
  114. <Tag size='large' color='grey' shape='circle'>
  115. {t('未测试')}
  116. </Tag>
  117. );
  118. } else if (responseTime <= 1000) {
  119. return (
  120. <Tag size='large' color='green' shape='circle'>
  121. {time}
  122. </Tag>
  123. );
  124. } else if (responseTime <= 3000) {
  125. return (
  126. <Tag size='large' color='lime' shape='circle'>
  127. {time}
  128. </Tag>
  129. );
  130. } else if (responseTime <= 5000) {
  131. return (
  132. <Tag size='large' color='yellow' shape='circle'>
  133. {time}
  134. </Tag>
  135. );
  136. } else {
  137. return (
  138. <Tag size='large' color='red' shape='circle'>
  139. {time}
  140. </Tag>
  141. );
  142. }
  143. };
  144. // Define column keys for selection
  145. const COLUMN_KEYS = {
  146. ID: 'id',
  147. NAME: 'name',
  148. GROUP: 'group',
  149. TYPE: 'type',
  150. STATUS: 'status',
  151. RESPONSE_TIME: 'response_time',
  152. BALANCE: 'balance',
  153. PRIORITY: 'priority',
  154. WEIGHT: 'weight',
  155. OPERATE: 'operate',
  156. };
  157. // State for column visibility
  158. const [visibleColumns, setVisibleColumns] = useState({});
  159. const [showColumnSelector, setShowColumnSelector] = useState(false);
  160. // Load saved column preferences from localStorage
  161. useEffect(() => {
  162. const savedColumns = localStorage.getItem('channels-table-columns');
  163. if (savedColumns) {
  164. try {
  165. const parsed = JSON.parse(savedColumns);
  166. // Make sure all columns are accounted for
  167. const defaults = getDefaultColumnVisibility();
  168. const merged = { ...defaults, ...parsed };
  169. setVisibleColumns(merged);
  170. } catch (e) {
  171. console.error('Failed to parse saved column preferences', e);
  172. initDefaultColumns();
  173. }
  174. } else {
  175. initDefaultColumns();
  176. }
  177. }, []);
  178. // Update table when column visibility changes
  179. useEffect(() => {
  180. if (Object.keys(visibleColumns).length > 0) {
  181. // Save to localStorage
  182. localStorage.setItem(
  183. 'channels-table-columns',
  184. JSON.stringify(visibleColumns),
  185. );
  186. }
  187. }, [visibleColumns]);
  188. // Get default column visibility
  189. const getDefaultColumnVisibility = () => {
  190. return {
  191. [COLUMN_KEYS.ID]: true,
  192. [COLUMN_KEYS.NAME]: true,
  193. [COLUMN_KEYS.GROUP]: true,
  194. [COLUMN_KEYS.TYPE]: true,
  195. [COLUMN_KEYS.STATUS]: true,
  196. [COLUMN_KEYS.RESPONSE_TIME]: true,
  197. [COLUMN_KEYS.BALANCE]: true,
  198. [COLUMN_KEYS.PRIORITY]: true,
  199. [COLUMN_KEYS.WEIGHT]: true,
  200. [COLUMN_KEYS.OPERATE]: true,
  201. };
  202. };
  203. // Initialize default column visibility
  204. const initDefaultColumns = () => {
  205. const defaults = getDefaultColumnVisibility();
  206. setVisibleColumns(defaults);
  207. };
  208. // Handle column visibility change
  209. const handleColumnVisibilityChange = (columnKey, checked) => {
  210. const updatedColumns = { ...visibleColumns, [columnKey]: checked };
  211. setVisibleColumns(updatedColumns);
  212. };
  213. // Handle "Select All" checkbox
  214. const handleSelectAll = (checked) => {
  215. const allKeys = Object.keys(COLUMN_KEYS).map((key) => COLUMN_KEYS[key]);
  216. const updatedColumns = {};
  217. allKeys.forEach((key) => {
  218. updatedColumns[key] = checked;
  219. });
  220. setVisibleColumns(updatedColumns);
  221. };
  222. // Define all columns with keys
  223. const allColumns = [
  224. {
  225. key: COLUMN_KEYS.ID,
  226. title: t('ID'),
  227. dataIndex: 'id',
  228. },
  229. {
  230. key: COLUMN_KEYS.NAME,
  231. title: t('名称'),
  232. dataIndex: 'name',
  233. },
  234. {
  235. key: COLUMN_KEYS.GROUP,
  236. title: t('分组'),
  237. dataIndex: 'group',
  238. render: (text, record, index) => (
  239. <div>
  240. <Space spacing={2}>
  241. {text
  242. ?.split(',')
  243. .sort((a, b) => {
  244. if (a === 'default') return -1;
  245. if (b === 'default') return 1;
  246. return a.localeCompare(b);
  247. })
  248. .map((item, index) => renderGroup(item))}
  249. </Space>
  250. </div>
  251. ),
  252. },
  253. {
  254. key: COLUMN_KEYS.TYPE,
  255. title: t('类型'),
  256. dataIndex: 'type',
  257. render: (text, record, index) => {
  258. if (record.children === undefined) {
  259. return <>{renderType(text)}</>;
  260. } else {
  261. return <>{renderTagType()}</>;
  262. }
  263. },
  264. },
  265. {
  266. key: COLUMN_KEYS.STATUS,
  267. title: t('状态'),
  268. dataIndex: 'status',
  269. render: (text, record, index) => {
  270. if (text === 3) {
  271. if (record.other_info === '') {
  272. record.other_info = '{}';
  273. }
  274. let otherInfo = JSON.parse(record.other_info);
  275. let reason = otherInfo['status_reason'];
  276. let time = otherInfo['status_time'];
  277. return (
  278. <div>
  279. <Tooltip
  280. content={t('原因:') + reason + t(',时间:') + timestamp2string(time)}
  281. >
  282. {renderStatus(text)}
  283. </Tooltip>
  284. </div>
  285. );
  286. } else {
  287. return renderStatus(text);
  288. }
  289. },
  290. },
  291. {
  292. key: COLUMN_KEYS.RESPONSE_TIME,
  293. title: t('响应时间'),
  294. dataIndex: 'response_time',
  295. render: (text, record, index) => (
  296. <div>{renderResponseTime(text)}</div>
  297. ),
  298. },
  299. {
  300. key: COLUMN_KEYS.BALANCE,
  301. title: t('已用/剩余'),
  302. dataIndex: 'expired_time',
  303. render: (text, record, index) => {
  304. if (record.children === undefined) {
  305. return (
  306. <div>
  307. <Space spacing={1}>
  308. <Tooltip content={t('已用额度')}>
  309. <Tag color='white' type='ghost' size='large' shape='circle'>
  310. {renderQuota(record.used_quota)}
  311. </Tag>
  312. </Tooltip>
  313. <Tooltip content={t('剩余额度') + record.balance + t(',点击更新')}>
  314. <Tag
  315. color='white'
  316. type='ghost'
  317. size='large'
  318. shape='circle'
  319. onClick={() => updateChannelBalance(record)}
  320. >
  321. ${renderNumberWithPoint(record.balance)}
  322. </Tag>
  323. </Tooltip>
  324. </Space>
  325. </div>
  326. );
  327. } else {
  328. return (
  329. <Tooltip content={t('已用额度')}>
  330. <Tag color='white' type='ghost' size='large' shape='circle'>
  331. {renderQuota(record.used_quota)}
  332. </Tag>
  333. </Tooltip>
  334. );
  335. }
  336. },
  337. },
  338. {
  339. key: COLUMN_KEYS.PRIORITY,
  340. title: t('优先级'),
  341. dataIndex: 'priority',
  342. render: (text, record, index) => {
  343. if (record.children === undefined) {
  344. return (
  345. <div>
  346. <InputNumber
  347. style={{ width: 70 }}
  348. name='priority'
  349. onBlur={(e) => {
  350. manageChannel(record.id, 'priority', record, e.target.value);
  351. }}
  352. keepFocus={true}
  353. innerButtons
  354. defaultValue={record.priority}
  355. min={-999}
  356. size="small"
  357. />
  358. </div>
  359. );
  360. } else {
  361. return (
  362. <InputNumber
  363. style={{ width: 70 }}
  364. name='priority'
  365. keepFocus={true}
  366. onBlur={(e) => {
  367. Modal.warning({
  368. title: t('修改子渠道优先级'),
  369. content: t('确定要修改所有子渠道优先级为 ') + e.target.value + t(' 吗?'),
  370. onOk: () => {
  371. if (e.target.value === '') {
  372. return;
  373. }
  374. submitTagEdit('priority', {
  375. tag: record.key,
  376. priority: e.target.value,
  377. });
  378. },
  379. });
  380. }}
  381. innerButtons
  382. defaultValue={record.priority}
  383. min={-999}
  384. size="small"
  385. />
  386. );
  387. }
  388. },
  389. },
  390. {
  391. key: COLUMN_KEYS.WEIGHT,
  392. title: t('权重'),
  393. dataIndex: 'weight',
  394. render: (text, record, index) => {
  395. if (record.children === undefined) {
  396. return (
  397. <div>
  398. <InputNumber
  399. style={{ width: 70 }}
  400. name='weight'
  401. onBlur={(e) => {
  402. manageChannel(record.id, 'weight', record, e.target.value);
  403. }}
  404. keepFocus={true}
  405. innerButtons
  406. defaultValue={record.weight}
  407. min={0}
  408. size="small"
  409. />
  410. </div>
  411. );
  412. } else {
  413. return (
  414. <InputNumber
  415. style={{ width: 70 }}
  416. name='weight'
  417. keepFocus={true}
  418. onBlur={(e) => {
  419. Modal.warning({
  420. title: t('修改子渠道权重'),
  421. content: t('确定要修改所有子渠道权重为 ') + e.target.value + t(' 吗?'),
  422. onOk: () => {
  423. if (e.target.value === '') {
  424. return;
  425. }
  426. submitTagEdit('weight', {
  427. tag: record.key,
  428. weight: e.target.value,
  429. });
  430. },
  431. });
  432. }}
  433. innerButtons
  434. defaultValue={record.weight}
  435. min={-999}
  436. size="small"
  437. />
  438. );
  439. }
  440. },
  441. },
  442. {
  443. key: COLUMN_KEYS.OPERATE,
  444. title: '',
  445. dataIndex: 'operate',
  446. fixed: 'right',
  447. render: (text, record, index) => {
  448. if (record.children === undefined) {
  449. // 创建更多操作的下拉菜单项
  450. const moreMenuItems = [
  451. {
  452. node: 'item',
  453. name: t('删除'),
  454. icon: <IconDelete />,
  455. type: 'danger',
  456. onClick: () => {
  457. Modal.confirm({
  458. title: t('确定是否要删除此渠道?'),
  459. content: t('此修改将不可逆'),
  460. onOk: () => {
  461. manageChannel(record.id, 'delete', record).then(() => {
  462. removeRecord(record);
  463. });
  464. },
  465. });
  466. },
  467. },
  468. {
  469. node: 'item',
  470. name: t('复制'),
  471. icon: <IconCopy />,
  472. type: 'primary',
  473. onClick: () => {
  474. Modal.confirm({
  475. title: t('确定是否要复制此渠道?'),
  476. content: t('复制渠道的所有信息'),
  477. onOk: () => copySelectedChannel(record),
  478. });
  479. },
  480. },
  481. ];
  482. return (
  483. <Space wrap>
  484. <SplitButtonGroup
  485. className="!rounded-full overflow-hidden"
  486. aria-label={t('测试单个渠道操作项目组')}
  487. >
  488. <Button
  489. theme='light'
  490. size="small"
  491. onClick={() => testChannel(record, '')}
  492. >
  493. {t('测试')}
  494. </Button>
  495. <Button
  496. theme='light'
  497. size="small"
  498. icon={<IconTreeTriangleDown />}
  499. onClick={() => {
  500. setCurrentTestChannel(record);
  501. setShowModelTestModal(true);
  502. }}
  503. />
  504. </SplitButtonGroup>
  505. {record.status === 1 ? (
  506. <Button
  507. theme='light'
  508. type='warning'
  509. size="small"
  510. className="!rounded-full"
  511. icon={<IconStop />}
  512. onClick={() => manageChannel(record.id, 'disable', record)}
  513. >
  514. {t('禁用')}
  515. </Button>
  516. ) : (
  517. <Button
  518. theme='light'
  519. type='secondary'
  520. size="small"
  521. className="!rounded-full"
  522. icon={<IconPlay />}
  523. onClick={() => manageChannel(record.id, 'enable', record)}
  524. >
  525. {t('启用')}
  526. </Button>
  527. )}
  528. <Button
  529. theme='light'
  530. type='tertiary'
  531. size="small"
  532. className="!rounded-full"
  533. icon={<IconEdit />}
  534. onClick={() => {
  535. setEditingChannel(record);
  536. setShowEdit(true);
  537. }}
  538. >
  539. {t('编辑')}
  540. </Button>
  541. <Dropdown
  542. trigger='click'
  543. position='bottomRight'
  544. menu={moreMenuItems}
  545. >
  546. <Button
  547. icon={<IconMore />}
  548. theme='light'
  549. type='tertiary'
  550. size="small"
  551. className="!rounded-full"
  552. />
  553. </Dropdown>
  554. </Space>
  555. );
  556. } else {
  557. // 标签操作的下拉菜单项
  558. const tagMenuItems = [
  559. {
  560. node: 'item',
  561. name: t('编辑'),
  562. icon: <IconEdit />,
  563. onClick: () => {
  564. setShowEditTag(true);
  565. setEditingTag(record.key);
  566. },
  567. },
  568. ];
  569. return (
  570. <Space wrap>
  571. <Button
  572. theme='light'
  573. type='secondary'
  574. size="small"
  575. className="!rounded-full"
  576. icon={<IconPlay />}
  577. onClick={() => manageTag(record.key, 'enable')}
  578. >
  579. {t('启用全部')}
  580. </Button>
  581. <Button
  582. theme='light'
  583. type='warning'
  584. size="small"
  585. className="!rounded-full"
  586. icon={<IconStop />}
  587. onClick={() => manageTag(record.key, 'disable')}
  588. >
  589. {t('禁用全部')}
  590. </Button>
  591. <Dropdown
  592. trigger='click'
  593. position='bottomRight'
  594. menu={tagMenuItems}
  595. >
  596. <Button
  597. icon={<IconMore />}
  598. theme='light'
  599. type='tertiary'
  600. size="small"
  601. className="!rounded-full"
  602. />
  603. </Dropdown>
  604. </Space>
  605. );
  606. }
  607. },
  608. },
  609. ];
  610. // Filter columns based on visibility settings
  611. const getVisibleColumns = () => {
  612. return allColumns.filter((column) => visibleColumns[column.key]);
  613. };
  614. // Column selector modal
  615. const renderColumnSelector = () => {
  616. return (
  617. <Modal
  618. title={t('列设置')}
  619. visible={showColumnSelector}
  620. onCancel={() => setShowColumnSelector(false)}
  621. footer={
  622. <div className="flex justify-end">
  623. <Button
  624. theme="light"
  625. onClick={() => initDefaultColumns()}
  626. className="!rounded-full"
  627. >
  628. {t('重置')}
  629. </Button>
  630. <Button
  631. theme="light"
  632. onClick={() => setShowColumnSelector(false)}
  633. className="!rounded-full"
  634. >
  635. {t('取消')}
  636. </Button>
  637. <Button
  638. type='primary'
  639. onClick={() => setShowColumnSelector(false)}
  640. className="!rounded-full"
  641. >
  642. {t('确定')}
  643. </Button>
  644. </div>
  645. }
  646. size="middle"
  647. centered={true}
  648. >
  649. <div style={{ marginBottom: 20 }}>
  650. <Checkbox
  651. checked={Object.values(visibleColumns).every((v) => v === true)}
  652. indeterminate={
  653. Object.values(visibleColumns).some((v) => v === true) &&
  654. !Object.values(visibleColumns).every((v) => v === true)
  655. }
  656. onChange={(e) => handleSelectAll(e.target.checked)}
  657. >
  658. {t('全选')}
  659. </Checkbox>
  660. </div>
  661. <div
  662. className="flex flex-wrap max-h-96 overflow-y-auto rounded-lg p-4"
  663. style={{ border: '1px solid var(--semi-color-border)' }}
  664. >
  665. {allColumns.map((column) => {
  666. // Skip columns without title
  667. if (!column.title) {
  668. return null;
  669. }
  670. return (
  671. <div
  672. key={column.key}
  673. className="w-1/2 mb-4 pr-2"
  674. >
  675. <Checkbox
  676. checked={!!visibleColumns[column.key]}
  677. onChange={(e) =>
  678. handleColumnVisibilityChange(column.key, e.target.checked)
  679. }
  680. >
  681. {column.title}
  682. </Checkbox>
  683. </div>
  684. );
  685. })}
  686. </div>
  687. </Modal>
  688. );
  689. };
  690. const [channels, setChannels] = useState([]);
  691. const [loading, setLoading] = useState(true);
  692. const [activePage, setActivePage] = useState(1);
  693. const [idSort, setIdSort] = useState(false);
  694. const [searchKeyword, setSearchKeyword] = useState('');
  695. const [searchGroup, setSearchGroup] = useState('');
  696. const [searchModel, setSearchModel] = useState('');
  697. const [searching, setSearching] = useState(false);
  698. const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
  699. const [channelCount, setChannelCount] = useState(pageSize);
  700. const [groupOptions, setGroupOptions] = useState([]);
  701. const [showEdit, setShowEdit] = useState(false);
  702. const [enableBatchDelete, setEnableBatchDelete] = useState(false);
  703. const [editingChannel, setEditingChannel] = useState({
  704. id: undefined,
  705. });
  706. const [showEditTag, setShowEditTag] = useState(false);
  707. const [editingTag, setEditingTag] = useState('');
  708. const [selectedChannels, setSelectedChannels] = useState([]);
  709. const [enableTagMode, setEnableTagMode] = useState(false);
  710. const [showBatchSetTag, setShowBatchSetTag] = useState(false);
  711. const [batchSetTagValue, setBatchSetTagValue] = useState('');
  712. const [showModelTestModal, setShowModelTestModal] = useState(false);
  713. const [currentTestChannel, setCurrentTestChannel] = useState(null);
  714. const [modelSearchKeyword, setModelSearchKeyword] = useState('');
  715. const [modelTestResults, setModelTestResults] = useState({});
  716. const [testingModels, setTestingModels] = useState(new Set());
  717. const [isBatchTesting, setIsBatchTesting] = useState(false);
  718. const [testQueue, setTestQueue] = useState([]);
  719. const [isProcessingQueue, setIsProcessingQueue] = useState(false);
  720. const removeRecord = (record) => {
  721. let newDataSource = [...channels];
  722. if (record.id != null) {
  723. let idx = newDataSource.findIndex((data) => {
  724. if (data.children !== undefined) {
  725. for (let i = 0; i < data.children.length; i++) {
  726. if (data.children[i].id === record.id) {
  727. data.children.splice(i, 1);
  728. return false;
  729. }
  730. }
  731. } else {
  732. return data.id === record.id;
  733. }
  734. });
  735. if (idx > -1) {
  736. newDataSource.splice(idx, 1);
  737. setChannels(newDataSource);
  738. }
  739. }
  740. };
  741. const setChannelFormat = (channels, enableTagMode) => {
  742. let channelDates = [];
  743. let channelTags = {};
  744. for (let i = 0; i < channels.length; i++) {
  745. channels[i].key = '' + channels[i].id;
  746. if (!enableTagMode) {
  747. channelDates.push(channels[i]);
  748. } else {
  749. let tag = channels[i].tag ? channels[i].tag : '';
  750. // find from channelTags
  751. let tagIndex = channelTags[tag];
  752. let tagChannelDates = undefined;
  753. if (tagIndex === undefined) {
  754. // not found, create a new tag
  755. channelTags[tag] = 1;
  756. tagChannelDates = {
  757. key: tag,
  758. id: tag,
  759. tag: tag,
  760. name: '标签:' + tag,
  761. group: '',
  762. used_quota: 0,
  763. response_time: 0,
  764. priority: -1,
  765. weight: -1,
  766. };
  767. tagChannelDates.children = [];
  768. channelDates.push(tagChannelDates);
  769. } else {
  770. // found, add to the tag
  771. tagChannelDates = channelDates.find((item) => item.key === tag);
  772. }
  773. if (tagChannelDates.priority === -1) {
  774. tagChannelDates.priority = channels[i].priority;
  775. } else {
  776. if (tagChannelDates.priority !== channels[i].priority) {
  777. tagChannelDates.priority = '';
  778. }
  779. }
  780. if (tagChannelDates.weight === -1) {
  781. tagChannelDates.weight = channels[i].weight;
  782. } else {
  783. if (tagChannelDates.weight !== channels[i].weight) {
  784. tagChannelDates.weight = '';
  785. }
  786. }
  787. if (tagChannelDates.group === '') {
  788. tagChannelDates.group = channels[i].group;
  789. } else {
  790. let channelGroupsStr = channels[i].group;
  791. channelGroupsStr.split(',').forEach((item, index) => {
  792. if (tagChannelDates.group.indexOf(item) === -1) {
  793. // join
  794. tagChannelDates.group += ',' + item;
  795. }
  796. });
  797. }
  798. tagChannelDates.children.push(channels[i]);
  799. if (channels[i].status === 1) {
  800. tagChannelDates.status = 1;
  801. }
  802. tagChannelDates.used_quota += channels[i].used_quota;
  803. tagChannelDates.response_time += channels[i].response_time;
  804. tagChannelDates.response_time = tagChannelDates.response_time / 2;
  805. }
  806. }
  807. // data.key = '' + data.id
  808. setChannels(channelDates);
  809. if (channelDates.length >= pageSize) {
  810. setChannelCount(channelDates.length + pageSize);
  811. } else {
  812. setChannelCount(channelDates.length);
  813. }
  814. };
  815. const loadChannels = async (startIdx, pageSize, idSort, enableTagMode) => {
  816. setLoading(true);
  817. const res = await API.get(
  818. `/api/channel/?p=${startIdx}&page_size=${pageSize}&id_sort=${idSort}&tag_mode=${enableTagMode}`,
  819. );
  820. if (res === undefined) {
  821. return;
  822. }
  823. const { success, message, data } = res.data;
  824. if (success) {
  825. if (startIdx === 0) {
  826. setChannelFormat(data, enableTagMode);
  827. } else {
  828. let newChannels = [...channels];
  829. newChannels.splice(startIdx * pageSize, data.length, ...data);
  830. setChannelFormat(newChannels, enableTagMode);
  831. }
  832. } else {
  833. showError(message);
  834. }
  835. setLoading(false);
  836. };
  837. const copySelectedChannel = async (record) => {
  838. const channelToCopy = { ...record };
  839. channelToCopy.name += t('_复制');
  840. channelToCopy.created_time = null;
  841. channelToCopy.balance = 0;
  842. channelToCopy.used_quota = 0;
  843. // 删除可能导致类型不匹配的字段
  844. delete channelToCopy.test_time;
  845. delete channelToCopy.response_time;
  846. if (!channelToCopy) {
  847. showError(t('渠道未找到,请刷新页面后重试。'));
  848. return;
  849. }
  850. try {
  851. const newChannel = { ...channelToCopy, id: undefined };
  852. const response = await API.post('/api/channel/', newChannel);
  853. if (response.data.success) {
  854. showSuccess(t('渠道复制成功'));
  855. await refresh();
  856. } else {
  857. showError(response.data.message);
  858. }
  859. } catch (error) {
  860. showError(t('渠道复制失败: ') + error.message);
  861. }
  862. };
  863. const refresh = async () => {
  864. if (searchKeyword === '' && searchGroup === '' && searchModel === '') {
  865. await loadChannels(activePage - 1, pageSize, idSort, enableTagMode);
  866. } else {
  867. await searchChannels(
  868. searchKeyword,
  869. searchGroup,
  870. searchModel,
  871. enableTagMode,
  872. );
  873. }
  874. };
  875. useEffect(() => {
  876. // console.log('default effect')
  877. const localIdSort = localStorage.getItem('id-sort') === 'true';
  878. const localPageSize =
  879. parseInt(localStorage.getItem('page-size')) || ITEMS_PER_PAGE;
  880. const localEnableTagMode = localStorage.getItem('enable-tag-mode') === 'true';
  881. const localEnableBatchDelete = localStorage.getItem('enable-batch-delete') === 'true';
  882. setIdSort(localIdSort);
  883. setPageSize(localPageSize);
  884. setEnableTagMode(localEnableTagMode);
  885. setEnableBatchDelete(localEnableBatchDelete);
  886. loadChannels(0, localPageSize, localIdSort, localEnableTagMode)
  887. .then()
  888. .catch((reason) => {
  889. showError(reason);
  890. });
  891. fetchGroups().then();
  892. loadChannelModels().then();
  893. }, []);
  894. const manageChannel = async (id, action, record, value) => {
  895. let data = { id };
  896. let res;
  897. switch (action) {
  898. case 'delete':
  899. res = await API.delete(`/api/channel/${id}/`);
  900. break;
  901. case 'enable':
  902. data.status = 1;
  903. res = await API.put('/api/channel/', data);
  904. break;
  905. case 'disable':
  906. data.status = 2;
  907. res = await API.put('/api/channel/', data);
  908. break;
  909. case 'priority':
  910. if (value === '') {
  911. return;
  912. }
  913. data.priority = parseInt(value);
  914. res = await API.put('/api/channel/', data);
  915. break;
  916. case 'weight':
  917. if (value === '') {
  918. return;
  919. }
  920. data.weight = parseInt(value);
  921. if (data.weight < 0) {
  922. data.weight = 0;
  923. }
  924. res = await API.put('/api/channel/', data);
  925. break;
  926. }
  927. const { success, message } = res.data;
  928. if (success) {
  929. showSuccess(t('操作成功完成!'));
  930. let channel = res.data.data;
  931. let newChannels = [...channels];
  932. if (action === 'delete') {
  933. } else {
  934. record.status = channel.status;
  935. }
  936. setChannels(newChannels);
  937. } else {
  938. showError(message);
  939. }
  940. };
  941. const manageTag = async (tag, action) => {
  942. console.log(tag, action);
  943. let res;
  944. switch (action) {
  945. case 'enable':
  946. res = await API.post('/api/channel/tag/enabled', {
  947. tag: tag,
  948. });
  949. break;
  950. case 'disable':
  951. res = await API.post('/api/channel/tag/disabled', {
  952. tag: tag,
  953. });
  954. break;
  955. }
  956. const { success, message } = res.data;
  957. if (success) {
  958. showSuccess('操作成功完成!');
  959. let newChannels = [...channels];
  960. for (let i = 0; i < newChannels.length; i++) {
  961. if (newChannels[i].tag === tag) {
  962. let status = action === 'enable' ? 1 : 2;
  963. newChannels[i]?.children?.forEach((channel) => {
  964. channel.status = status;
  965. });
  966. newChannels[i].status = status;
  967. }
  968. }
  969. setChannels(newChannels);
  970. } else {
  971. showError(message);
  972. }
  973. };
  974. const searchChannels = async (
  975. searchKeyword,
  976. searchGroup,
  977. searchModel,
  978. enableTagMode,
  979. ) => {
  980. if (searchKeyword === '' && searchGroup === '' && searchModel === '') {
  981. await loadChannels(activePage - 1, pageSize, idSort, enableTagMode);
  982. // setActivePage(1);
  983. return;
  984. }
  985. setSearching(true);
  986. const res = await API.get(
  987. `/api/channel/search?keyword=${searchKeyword}&group=${searchGroup}&model=${searchModel}&id_sort=${idSort}&tag_mode=${enableTagMode}`,
  988. );
  989. const { success, message, data } = res.data;
  990. if (success) {
  991. setChannelFormat(data, enableTagMode);
  992. setActivePage(1);
  993. } else {
  994. showError(message);
  995. }
  996. setSearching(false);
  997. };
  998. const updateChannelProperty = (channelId, updateFn) => {
  999. // Create a new copy of channels array
  1000. const newChannels = [...channels];
  1001. let updated = false;
  1002. // Find and update the correct channel
  1003. newChannels.forEach((channel) => {
  1004. if (channel.children !== undefined) {
  1005. // If this is a tag group, search in its children
  1006. channel.children.forEach((child) => {
  1007. if (child.id === channelId) {
  1008. updateFn(child);
  1009. updated = true;
  1010. }
  1011. });
  1012. } else if (channel.id === channelId) {
  1013. // Direct channel match
  1014. updateFn(channel);
  1015. updated = true;
  1016. }
  1017. });
  1018. // Only update state if we actually modified a channel
  1019. if (updated) {
  1020. setChannels(newChannels);
  1021. }
  1022. };
  1023. const processTestQueue = async () => {
  1024. if (!isProcessingQueue || testQueue.length === 0) return;
  1025. const { channel, model } = testQueue[0];
  1026. try {
  1027. setTestingModels(prev => new Set([...prev, model]));
  1028. const res = await API.get(`/api/channel/test/${channel.id}?model=${model}`);
  1029. const { success, message, time } = res.data;
  1030. setModelTestResults(prev => ({
  1031. ...prev,
  1032. [`${channel.id}-${model}`]: { success, time }
  1033. }));
  1034. if (success) {
  1035. updateChannelProperty(channel.id, (ch) => {
  1036. ch.response_time = time * 1000;
  1037. ch.test_time = Date.now() / 1000;
  1038. });
  1039. if (!model) {
  1040. showInfo(
  1041. t('通道 ${name} 测试成功,耗时 ${time.toFixed(2)} 秒。')
  1042. .replace('${name}', channel.name)
  1043. .replace('${time.toFixed(2)}', time.toFixed(2)),
  1044. );
  1045. }
  1046. } else {
  1047. showError(message);
  1048. }
  1049. } catch (error) {
  1050. showError(error.message);
  1051. } finally {
  1052. setTestingModels(prev => {
  1053. const newSet = new Set(prev);
  1054. newSet.delete(model);
  1055. return newSet;
  1056. });
  1057. }
  1058. // 移除已处理的测试
  1059. setTestQueue(prev => prev.slice(1));
  1060. };
  1061. // 监听队列变化
  1062. useEffect(() => {
  1063. if (testQueue.length > 0 && isProcessingQueue) {
  1064. processTestQueue();
  1065. } else if (testQueue.length === 0 && isProcessingQueue) {
  1066. setIsProcessingQueue(false);
  1067. setIsBatchTesting(false);
  1068. }
  1069. }, [testQueue, isProcessingQueue]);
  1070. const testChannel = async (record, model) => {
  1071. setTestQueue(prev => [...prev, { channel: record, model }]);
  1072. if (!isProcessingQueue) {
  1073. setIsProcessingQueue(true);
  1074. }
  1075. };
  1076. const batchTestModels = async () => {
  1077. if (!currentTestChannel) return;
  1078. setIsBatchTesting(true);
  1079. const models = currentTestChannel.models
  1080. .split(',')
  1081. .filter((model) =>
  1082. model.toLowerCase().includes(modelSearchKeyword.toLowerCase())
  1083. );
  1084. setTestQueue(models.map(model => ({
  1085. channel: currentTestChannel,
  1086. model
  1087. })));
  1088. setIsProcessingQueue(true);
  1089. };
  1090. const handleCloseModal = () => {
  1091. if (isBatchTesting) {
  1092. // 清空测试队列来停止测试
  1093. setTestQueue([]);
  1094. setIsProcessingQueue(false);
  1095. setIsBatchTesting(false);
  1096. showSuccess(t('已停止测试'));
  1097. } else {
  1098. setShowModelTestModal(false);
  1099. setModelSearchKeyword('');
  1100. }
  1101. };
  1102. let pageData = channels.slice(
  1103. (activePage - 1) * pageSize,
  1104. activePage * pageSize,
  1105. );
  1106. const handlePageChange = (page) => {
  1107. setActivePage(page);
  1108. if (page === Math.ceil(channels.length / pageSize) + 1) {
  1109. // In this case we have to load more data and then append them.
  1110. loadChannels(page - 1, pageSize, idSort, enableTagMode).then((r) => { });
  1111. }
  1112. };
  1113. const handlePageSizeChange = async (size) => {
  1114. localStorage.setItem('page-size', size + '');
  1115. setPageSize(size);
  1116. setActivePage(1);
  1117. loadChannels(0, size, idSort, enableTagMode)
  1118. .then()
  1119. .catch((reason) => {
  1120. showError(reason);
  1121. });
  1122. };
  1123. const fetchGroups = async () => {
  1124. try {
  1125. let res = await API.get(`/api/group/`);
  1126. // add 'all' option
  1127. // res.data.data.unshift('all');
  1128. if (res === undefined) {
  1129. return;
  1130. }
  1131. setGroupOptions(
  1132. res.data.data.map((group) => ({
  1133. label: group,
  1134. value: group,
  1135. })),
  1136. );
  1137. } catch (error) {
  1138. showError(error.message);
  1139. }
  1140. };
  1141. const submitTagEdit = async (type, data) => {
  1142. switch (type) {
  1143. case 'priority':
  1144. if (data.priority === undefined || data.priority === '') {
  1145. showInfo('优先级必须是整数!');
  1146. return;
  1147. }
  1148. data.priority = parseInt(data.priority);
  1149. break;
  1150. case 'weight':
  1151. if (
  1152. data.weight === undefined ||
  1153. data.weight < 0 ||
  1154. data.weight === ''
  1155. ) {
  1156. showInfo('权重必须是非负整数!');
  1157. return;
  1158. }
  1159. data.weight = parseInt(data.weight);
  1160. break;
  1161. }
  1162. try {
  1163. const res = await API.put('/api/channel/tag', data);
  1164. if (res?.data?.success) {
  1165. showSuccess('更新成功!');
  1166. await refresh();
  1167. }
  1168. } catch (error) {
  1169. showError(error);
  1170. }
  1171. };
  1172. const closeEdit = () => {
  1173. setShowEdit(false);
  1174. };
  1175. const handleRow = (record, index) => {
  1176. if (record.status !== 1) {
  1177. return {
  1178. style: {
  1179. background: 'var(--semi-color-disabled-border)',
  1180. },
  1181. };
  1182. } else {
  1183. return {};
  1184. }
  1185. };
  1186. const batchSetChannelTag = async () => {
  1187. if (selectedChannels.length === 0) {
  1188. showError(t('请先选择要设置标签的渠道!'));
  1189. return;
  1190. }
  1191. if (batchSetTagValue === '') {
  1192. showError(t('标签不能为空!'));
  1193. return;
  1194. }
  1195. let ids = selectedChannels.map((channel) => channel.id);
  1196. const res = await API.post('/api/channel/batch/tag', {
  1197. ids: ids,
  1198. tag: batchSetTagValue === '' ? null : batchSetTagValue,
  1199. });
  1200. if (res.data.success) {
  1201. showSuccess(
  1202. t('已为 ${count} 个渠道设置标签!').replace('${count}', res.data.data),
  1203. );
  1204. await refresh();
  1205. setShowBatchSetTag(false);
  1206. } else {
  1207. showError(res.data.message);
  1208. }
  1209. };
  1210. const testAllChannels = async () => {
  1211. const res = await API.get(`/api/channel/test`);
  1212. const { success, message } = res.data;
  1213. if (success) {
  1214. showInfo(t('已成功开始测试所有已启用通道,请刷新页面查看结果。'));
  1215. } else {
  1216. showError(message);
  1217. }
  1218. };
  1219. const deleteAllDisabledChannels = async () => {
  1220. const res = await API.delete(`/api/channel/disabled`);
  1221. const { success, message, data } = res.data;
  1222. if (success) {
  1223. showSuccess(
  1224. t('已删除所有禁用渠道,共计 ${data} 个').replace('${data}', data),
  1225. );
  1226. await refresh();
  1227. } else {
  1228. showError(message);
  1229. }
  1230. };
  1231. const updateAllChannelsBalance = async () => {
  1232. const res = await API.get(`/api/channel/update_balance`);
  1233. const { success, message } = res.data;
  1234. if (success) {
  1235. showInfo(t('已更新完毕所有已启用通道余额!'));
  1236. } else {
  1237. showError(message);
  1238. }
  1239. };
  1240. const updateChannelBalance = async (record) => {
  1241. const res = await API.get(`/api/channel/update_balance/${record.id}/`);
  1242. const { success, message, balance } = res.data;
  1243. if (success) {
  1244. updateChannelProperty(record.id, (channel) => {
  1245. channel.balance = balance;
  1246. channel.balance_updated_time = Date.now() / 1000;
  1247. });
  1248. showInfo(
  1249. t('通道 ${name} 余额更新成功!').replace('${name}', record.name),
  1250. );
  1251. } else {
  1252. showError(message);
  1253. }
  1254. };
  1255. const batchDeleteChannels = async () => {
  1256. if (selectedChannels.length === 0) {
  1257. showError(t('请先选择要删除的通道!'));
  1258. return;
  1259. }
  1260. setLoading(true);
  1261. let ids = [];
  1262. selectedChannels.forEach((channel) => {
  1263. ids.push(channel.id);
  1264. });
  1265. const res = await API.post(`/api/channel/batch`, { ids: ids });
  1266. const { success, message, data } = res.data;
  1267. if (success) {
  1268. showSuccess(t('已删除 ${data} 个通道!').replace('${data}', data));
  1269. await refresh();
  1270. } else {
  1271. showError(message);
  1272. }
  1273. setLoading(false);
  1274. };
  1275. const fixChannelsAbilities = async () => {
  1276. const res = await API.post(`/api/channel/fix`);
  1277. const { success, message, data } = res.data;
  1278. if (success) {
  1279. showSuccess(t('已修复 ${data} 个通道!').replace('${data}', data));
  1280. await refresh();
  1281. } else {
  1282. showError(message);
  1283. }
  1284. };
  1285. const renderHeader = () => (
  1286. <div className="flex flex-col w-full">
  1287. <div className="flex flex-col md:flex-row justify-between gap-4">
  1288. <div className="flex flex-wrap md:flex-nowrap items-center gap-2 w-full md:w-auto order-2 md:order-1">
  1289. <Button
  1290. disabled={!enableBatchDelete}
  1291. theme='light'
  1292. type='danger'
  1293. className="!rounded-full w-full md:w-auto"
  1294. onClick={() => {
  1295. Modal.confirm({
  1296. title: t('确定是否要删除所选通道?'),
  1297. content: t('此修改将不可逆'),
  1298. onOk: () => batchDeleteChannels(),
  1299. });
  1300. }}
  1301. >
  1302. {t('删除所选通道')}
  1303. </Button>
  1304. <Button
  1305. disabled={!enableBatchDelete}
  1306. theme='light'
  1307. type='primary'
  1308. onClick={() => setShowBatchSetTag(true)}
  1309. className="!rounded-full w-full md:w-auto"
  1310. >
  1311. {t('批量设置标签')}
  1312. </Button>
  1313. <Dropdown
  1314. trigger='click'
  1315. render={
  1316. <Dropdown.Menu>
  1317. <Dropdown.Item>
  1318. <Button
  1319. theme='light'
  1320. type='warning'
  1321. className="!rounded-full w-full"
  1322. onClick={() => {
  1323. Modal.confirm({
  1324. title: t('确定?'),
  1325. content: t('确定要测试所有通道吗?'),
  1326. onOk: () => testAllChannels(),
  1327. size: 'small',
  1328. centered: true,
  1329. });
  1330. }}
  1331. >
  1332. {t('测试所有通道')}
  1333. </Button>
  1334. </Dropdown.Item>
  1335. <Dropdown.Item>
  1336. <Button
  1337. theme='light'
  1338. type='secondary'
  1339. className="!rounded-full w-full"
  1340. onClick={() => {
  1341. Modal.confirm({
  1342. title: t('确定?'),
  1343. content: t('确定要更新所有已启用通道余额吗?'),
  1344. onOk: () => updateAllChannelsBalance(),
  1345. size: 'sm',
  1346. centered: true,
  1347. });
  1348. }}
  1349. >
  1350. {t('更新所有已启用通道余额')}
  1351. </Button>
  1352. </Dropdown.Item>
  1353. <Dropdown.Item>
  1354. <Button
  1355. theme='light'
  1356. type='danger'
  1357. className="!rounded-full w-full"
  1358. onClick={() => {
  1359. Modal.confirm({
  1360. title: t('确定是否要删除禁用通道?'),
  1361. content: t('此修改将不可逆'),
  1362. onOk: () => deleteAllDisabledChannels(),
  1363. size: 'sm',
  1364. centered: true,
  1365. });
  1366. }}
  1367. >
  1368. {t('删除禁用通道')}
  1369. </Button>
  1370. </Dropdown.Item>
  1371. <Dropdown.Item>
  1372. <Button
  1373. theme='light'
  1374. type='tertiary'
  1375. className="!rounded-full w-full"
  1376. onClick={() => {
  1377. Modal.confirm({
  1378. title: t('确定是否要修复数据库一致性?'),
  1379. content: t('进行该操作时,可能导致渠道访问错误,请仅在数据库出现问题时使用'),
  1380. onOk: () => fixChannelsAbilities(),
  1381. size: 'sm',
  1382. centered: true,
  1383. });
  1384. }}
  1385. >
  1386. {t('修复数据库一致性')}
  1387. </Button>
  1388. </Dropdown.Item>
  1389. </Dropdown.Menu>
  1390. }
  1391. >
  1392. <Button theme='light' type='tertiary' icon={<IconSetting />} className="!rounded-full w-full md:w-auto">
  1393. {t('批量操作')}
  1394. </Button>
  1395. </Dropdown>
  1396. </div>
  1397. <div className="flex flex-col md:flex-row items-start md:items-center gap-4 w-full md:w-auto order-1 md:order-2">
  1398. <div className="flex items-center justify-between w-full md:w-auto">
  1399. <Typography.Text strong className="mr-2">
  1400. {t('使用ID排序')}
  1401. </Typography.Text>
  1402. <Switch
  1403. checked={idSort}
  1404. onChange={(v) => {
  1405. localStorage.setItem('id-sort', v + '');
  1406. setIdSort(v);
  1407. loadChannels(0, pageSize, v, enableTagMode);
  1408. }}
  1409. />
  1410. </div>
  1411. <div className="flex items-center justify-between w-full md:w-auto">
  1412. <Typography.Text strong className="mr-2">
  1413. {t('开启批量操作')}
  1414. </Typography.Text>
  1415. <Switch
  1416. checked={enableBatchDelete}
  1417. onChange={(v) => {
  1418. localStorage.setItem('enable-batch-delete', v + '');
  1419. setEnableBatchDelete(v);
  1420. }}
  1421. />
  1422. </div>
  1423. <div className="flex items-center justify-between w-full md:w-auto">
  1424. <Typography.Text strong className="mr-2">
  1425. {t('标签聚合模式')}
  1426. </Typography.Text>
  1427. <Switch
  1428. checked={enableTagMode}
  1429. onChange={(v) => {
  1430. localStorage.setItem('enable-tag-mode', v + '');
  1431. setEnableTagMode(v);
  1432. loadChannels(0, pageSize, idSort, v);
  1433. }}
  1434. />
  1435. </div>
  1436. </div>
  1437. </div>
  1438. <Divider margin="12px" />
  1439. <div className="flex flex-col md:flex-row justify-between items-center gap-4 w-full">
  1440. <div className="flex gap-2 w-full md:w-auto order-2 md:order-1">
  1441. <Button
  1442. theme='light'
  1443. type='primary'
  1444. icon={<IconPlus />}
  1445. className="!rounded-full w-full md:w-auto"
  1446. onClick={() => {
  1447. setEditingChannel({
  1448. id: undefined,
  1449. });
  1450. setShowEdit(true);
  1451. }}
  1452. >
  1453. {t('添加渠道')}
  1454. </Button>
  1455. <Button
  1456. theme='light'
  1457. type='primary'
  1458. icon={<IconRefresh />}
  1459. className="!rounded-full w-full md:w-auto"
  1460. onClick={refresh}
  1461. >
  1462. {t('刷新')}
  1463. </Button>
  1464. <Button
  1465. theme='light'
  1466. type='tertiary'
  1467. icon={<IconSetting />}
  1468. onClick={() => setShowColumnSelector(true)}
  1469. className="!rounded-full w-full md:w-auto"
  1470. >
  1471. {t('列设置')}
  1472. </Button>
  1473. </div>
  1474. <div className="flex flex-col md:flex-row items-center gap-4 w-full md:w-auto order-1 md:order-2">
  1475. <div className="relative w-full md:w-64">
  1476. <Input
  1477. prefix={<IconSearch />}
  1478. placeholder={t('搜索渠道的 ID,名称,密钥和API地址 ...')}
  1479. value={searchKeyword}
  1480. loading={searching}
  1481. onChange={(v) => {
  1482. setSearchKeyword(v.trim());
  1483. }}
  1484. className="!rounded-full"
  1485. showClear
  1486. />
  1487. </div>
  1488. <div className="w-full md:w-48">
  1489. <Input
  1490. prefix={<IconFilter />}
  1491. placeholder={t('模型关键字')}
  1492. value={searchModel}
  1493. loading={searching}
  1494. onChange={(v) => {
  1495. setSearchModel(v.trim());
  1496. }}
  1497. className="!rounded-full"
  1498. showClear
  1499. />
  1500. </div>
  1501. <div className="w-full md:w-48">
  1502. <Select
  1503. placeholder={t('选择分组')}
  1504. optionList={[
  1505. { label: t('选择分组'), value: null },
  1506. ...groupOptions,
  1507. ]}
  1508. value={searchGroup}
  1509. onChange={(v) => {
  1510. setSearchGroup(v);
  1511. searchChannels(searchKeyword, v, searchModel, enableTagMode);
  1512. }}
  1513. className="!rounded-full w-full"
  1514. showClear
  1515. />
  1516. </div>
  1517. <Button
  1518. type="primary"
  1519. onClick={() => {
  1520. searchChannels(searchKeyword, searchGroup, searchModel, enableTagMode);
  1521. }}
  1522. loading={searching}
  1523. className="!rounded-full w-full md:w-auto"
  1524. >
  1525. {t('查询')}
  1526. </Button>
  1527. </div>
  1528. </div>
  1529. </div>
  1530. );
  1531. return (
  1532. <>
  1533. {renderColumnSelector()}
  1534. <EditTagModal
  1535. visible={showEditTag}
  1536. tag={editingTag}
  1537. handleClose={() => setShowEditTag(false)}
  1538. refresh={refresh}
  1539. />
  1540. <EditChannel
  1541. refresh={refresh}
  1542. visible={showEdit}
  1543. handleClose={closeEdit}
  1544. editingChannel={editingChannel}
  1545. />
  1546. <Card
  1547. className="!rounded-2xl"
  1548. title={renderHeader()}
  1549. shadows='always'
  1550. bordered={false}
  1551. >
  1552. <div style={{ overflow: 'auto' }}>
  1553. <Table
  1554. columns={getVisibleColumns()}
  1555. dataSource={pageData}
  1556. scroll={{ x: 'max-content' }}
  1557. pagination={{
  1558. currentPage: activePage,
  1559. pageSize: pageSize,
  1560. total: channelCount,
  1561. pageSizeOpts: [10, 20, 50, 100],
  1562. showSizeChanger: true,
  1563. formatPageText: (page) => t('第 {{start}} - {{end}} 条,共 {{total}} 条', {
  1564. start: page.currentStart,
  1565. end: page.currentEnd,
  1566. total: channels.length,
  1567. }),
  1568. onPageSizeChange: (size) => {
  1569. handlePageSizeChange(size);
  1570. },
  1571. onPageChange: handlePageChange,
  1572. }}
  1573. expandAllRows={false}
  1574. onRow={handleRow}
  1575. rowSelection={
  1576. enableBatchDelete
  1577. ? {
  1578. onChange: (selectedRowKeys, selectedRows) => {
  1579. setSelectedChannels(selectedRows);
  1580. },
  1581. }
  1582. : null
  1583. }
  1584. className="rounded-xl overflow-hidden"
  1585. size="middle"
  1586. loading={loading}
  1587. />
  1588. </div>
  1589. </Card>
  1590. {/* 批量设置标签模态框 */}
  1591. <Modal
  1592. title={t('批量设置标签')}
  1593. visible={showBatchSetTag}
  1594. onOk={batchSetChannelTag}
  1595. onCancel={() => setShowBatchSetTag(false)}
  1596. maskClosable={false}
  1597. centered={true}
  1598. size="small"
  1599. className="!rounded-lg"
  1600. >
  1601. <div className="mb-5">
  1602. <Typography.Text>{t('请输入要设置的标签名称')}</Typography.Text>
  1603. </div>
  1604. <Input
  1605. placeholder={t('请输入标签名称')}
  1606. value={batchSetTagValue}
  1607. onChange={(v) => setBatchSetTagValue(v)}
  1608. size='large'
  1609. className="!rounded-full"
  1610. />
  1611. <div className="mt-4">
  1612. <Typography.Text type='secondary'>
  1613. {t('已选择 ${count} 个渠道').replace('${count}', selectedChannels.length)}
  1614. </Typography.Text>
  1615. </div>
  1616. </Modal>
  1617. {/* 模型测试弹窗 */}
  1618. <Modal
  1619. title={
  1620. currentTestChannel && (
  1621. <div className="flex items-center gap-2">
  1622. <Typography.Text strong className="!text-[var(--semi-color-text-0)] !text-base">
  1623. {currentTestChannel.name} {t('渠道的模型测试')}
  1624. </Typography.Text>
  1625. <Typography.Text type="tertiary" className="!text-xs flex items-center">
  1626. {t('共')} {currentTestChannel.models.split(',').length} {t('个模型')}
  1627. </Typography.Text>
  1628. </div>
  1629. )
  1630. }
  1631. visible={showModelTestModal && currentTestChannel !== null}
  1632. onCancel={handleCloseModal}
  1633. footer={
  1634. <div className="flex justify-end">
  1635. {isBatchTesting ? (
  1636. <Button
  1637. theme='light'
  1638. type='warning'
  1639. className="!rounded-full"
  1640. onClick={handleCloseModal}
  1641. >
  1642. {t('停止测试')}
  1643. </Button>
  1644. ) : (
  1645. <Button
  1646. theme='light'
  1647. type='tertiary'
  1648. className="!rounded-full"
  1649. onClick={handleCloseModal}
  1650. >
  1651. {t('取消')}
  1652. </Button>
  1653. )}
  1654. <Button
  1655. theme='light'
  1656. type='primary'
  1657. className="!rounded-full"
  1658. onClick={batchTestModels}
  1659. loading={isBatchTesting}
  1660. disabled={isBatchTesting}
  1661. >
  1662. {isBatchTesting ? t('测试中...') : t('批量测试${count}个模型').replace(
  1663. '${count}',
  1664. currentTestChannel
  1665. ? currentTestChannel.models
  1666. .split(',')
  1667. .filter((model) =>
  1668. model.toLowerCase().includes(modelSearchKeyword.toLowerCase())
  1669. ).length
  1670. : 0
  1671. )}
  1672. </Button>
  1673. </div>
  1674. }
  1675. maskClosable={!isBatchTesting}
  1676. centered={true}
  1677. className="!rounded-lg"
  1678. size="large"
  1679. >
  1680. <div className="max-h-[600px] overflow-y-auto">
  1681. {currentTestChannel && (
  1682. <div>
  1683. <div className="flex items-center justify-end mb-2">
  1684. <Input
  1685. placeholder={t('搜索模型...')}
  1686. value={modelSearchKeyword}
  1687. onChange={(v) => setModelSearchKeyword(v)}
  1688. className="w-64 !rounded-full"
  1689. prefix={<IconSearch />}
  1690. showClear
  1691. />
  1692. </div>
  1693. <Table
  1694. columns={[
  1695. {
  1696. title: t('模型名称'),
  1697. dataIndex: 'model',
  1698. render: (text) => (
  1699. <div className="flex items-center">
  1700. <Typography.Text strong>{text}</Typography.Text>
  1701. </div>
  1702. )
  1703. },
  1704. {
  1705. title: t('状态'),
  1706. dataIndex: 'status',
  1707. render: (text, record) => {
  1708. const testResult = modelTestResults[`${currentTestChannel.id}-${record.model}`];
  1709. const isTesting = testingModels.has(record.model);
  1710. if (isTesting) {
  1711. return (
  1712. <Tag size='large' color='blue' className="!rounded-full">
  1713. {t('测试中')}
  1714. </Tag>
  1715. );
  1716. }
  1717. if (!testResult) {
  1718. return (
  1719. <Tag size='large' color='grey' className="!rounded-full">
  1720. {t('未开始')}
  1721. </Tag>
  1722. );
  1723. }
  1724. return (
  1725. <div className="flex items-center gap-2">
  1726. <Tag
  1727. size='large'
  1728. color={testResult.success ? 'green' : 'red'}
  1729. className="!rounded-full"
  1730. >
  1731. {testResult.success ? t('成功') : t('失败')}
  1732. </Tag>
  1733. {testResult.success && (
  1734. <Typography.Text type="tertiary">
  1735. {t('请求时长: ${time}s').replace('${time}', testResult.time.toFixed(2))}
  1736. </Typography.Text>
  1737. )}
  1738. </div>
  1739. );
  1740. }
  1741. },
  1742. {
  1743. title: '',
  1744. dataIndex: 'operate',
  1745. render: (text, record) => {
  1746. const isTesting = testingModels.has(record.model);
  1747. return (
  1748. <Button
  1749. theme='light'
  1750. type='primary'
  1751. className="!rounded-full"
  1752. onClick={() => testChannel(currentTestChannel, record.model)}
  1753. loading={isTesting}
  1754. size='small'
  1755. icon={<IconSmallTriangleRight />}
  1756. >
  1757. {t('测试')}
  1758. </Button>
  1759. );
  1760. }
  1761. }
  1762. ]}
  1763. dataSource={currentTestChannel.models
  1764. .split(',')
  1765. .filter((model) =>
  1766. model.toLowerCase().includes(modelSearchKeyword.toLowerCase())
  1767. )
  1768. .map((model) => ({
  1769. model,
  1770. key: model
  1771. }))}
  1772. pagination={false}
  1773. size="middle"
  1774. />
  1775. </div>
  1776. )}
  1777. </div>
  1778. </Modal>
  1779. </>
  1780. );
  1781. };
  1782. export default ChannelsTable;