ChannelsTable.js 45 KB

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