ChannelsTable.js 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  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: isMobile() ? '90%' : 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={{
  614. width: isMobile() ? '100%' : '50%',
  615. marginBottom: 16,
  616. paddingRight: 8
  617. }}>
  618. <Checkbox
  619. checked={!!visibleColumns[column.key]}
  620. onChange={e => handleColumnVisibilityChange(column.key, e.target.checked)}
  621. >
  622. {column.title}
  623. </Checkbox>
  624. </div>
  625. );
  626. })}
  627. </div>
  628. </Modal>
  629. );
  630. };
  631. const [channels, setChannels] = useState([]);
  632. const [loading, setLoading] = useState(true);
  633. const [activePage, setActivePage] = useState(1);
  634. const [idSort, setIdSort] = useState(false);
  635. const [searchKeyword, setSearchKeyword] = useState('');
  636. const [searchGroup, setSearchGroup] = useState('');
  637. const [searchModel, setSearchModel] = useState('');
  638. const [searching, setSearching] = useState(false);
  639. const [updatingBalance, setUpdatingBalance] = useState(false);
  640. const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
  641. const [showPrompt, setShowPrompt] = useState(
  642. shouldShowPrompt('channel-test')
  643. );
  644. const [channelCount, setChannelCount] = useState(pageSize);
  645. const [groupOptions, setGroupOptions] = useState([]);
  646. const [showEdit, setShowEdit] = useState(false);
  647. const [enableBatchDelete, setEnableBatchDelete] = useState(false);
  648. const [editingChannel, setEditingChannel] = useState({
  649. id: undefined
  650. });
  651. const [showEditTag, setShowEditTag] = useState(false);
  652. const [editingTag, setEditingTag] = useState('');
  653. const [selectedChannels, setSelectedChannels] = useState([]);
  654. const [showEditPriority, setShowEditPriority] = useState(false);
  655. const [enableTagMode, setEnableTagMode] = useState(false);
  656. const [showBatchSetTag, setShowBatchSetTag] = useState(false);
  657. const [batchSetTagValue, setBatchSetTagValue] = useState('');
  658. const [showModelTestModal, setShowModelTestModal] = useState(false);
  659. const [currentTestChannel, setCurrentTestChannel] = useState(null);
  660. const [modelSearchKeyword, setModelSearchKeyword] = useState('');
  661. const removeRecord = (record) => {
  662. let newDataSource = [...channels];
  663. if (record.id != null) {
  664. let idx = newDataSource.findIndex((data) => {
  665. if (data.children !== undefined) {
  666. for (let i = 0; i < data.children.length; i++) {
  667. if (data.children[i].id === record.id) {
  668. data.children.splice(i, 1);
  669. return false;
  670. }
  671. }
  672. } else {
  673. return data.id === record.id
  674. }
  675. });
  676. if (idx > -1) {
  677. newDataSource.splice(idx, 1);
  678. setChannels(newDataSource);
  679. }
  680. }
  681. };
  682. const setChannelFormat = (channels, enableTagMode) => {
  683. let channelDates = [];
  684. let channelTags = {};
  685. for (let i = 0; i < channels.length; i++) {
  686. channels[i].key = '' + channels[i].id;
  687. if (!enableTagMode) {
  688. channelDates.push(channels[i]);
  689. } else {
  690. let tag = channels[i].tag ? channels[i].tag : "";
  691. // find from channelTags
  692. let tagIndex = channelTags[tag];
  693. let tagChannelDates = undefined;
  694. if (tagIndex === undefined) {
  695. // not found, create a new tag
  696. channelTags[tag] = 1;
  697. tagChannelDates = {
  698. key: tag,
  699. id: tag,
  700. tag: tag,
  701. name: '标签:' + tag,
  702. group: '',
  703. used_quota: 0,
  704. response_time: 0,
  705. priority: -1,
  706. weight: -1,
  707. };
  708. tagChannelDates.children = [];
  709. channelDates.push(tagChannelDates);
  710. } else {
  711. // found, add to the tag
  712. tagChannelDates = channelDates.find((item) => item.key === tag);
  713. }
  714. if (tagChannelDates.priority === -1) {
  715. tagChannelDates.priority = channels[i].priority;
  716. } else {
  717. if (tagChannelDates.priority !== channels[i].priority) {
  718. tagChannelDates.priority = '';
  719. }
  720. }
  721. if (tagChannelDates.weight === -1) {
  722. tagChannelDates.weight = channels[i].weight;
  723. } else {
  724. if (tagChannelDates.weight !== channels[i].weight) {
  725. tagChannelDates.weight = '';
  726. }
  727. }
  728. if (tagChannelDates.group === '') {
  729. tagChannelDates.group = channels[i].group;
  730. } else {
  731. let channelGroupsStr = channels[i].group;
  732. channelGroupsStr.split(',').forEach((item, index) => {
  733. if (tagChannelDates.group.indexOf(item) === -1) {
  734. // join
  735. tagChannelDates.group += ',' + item;
  736. }
  737. });
  738. }
  739. tagChannelDates.children.push(channels[i]);
  740. if (channels[i].status === 1) {
  741. tagChannelDates.status = 1;
  742. }
  743. tagChannelDates.used_quota += channels[i].used_quota;
  744. tagChannelDates.response_time += channels[i].response_time;
  745. tagChannelDates.response_time = tagChannelDates.response_time / 2;
  746. }
  747. }
  748. // data.key = '' + data.id
  749. setChannels(channelDates);
  750. if (channelDates.length >= pageSize) {
  751. setChannelCount(channelDates.length + pageSize);
  752. } else {
  753. setChannelCount(channelDates.length);
  754. }
  755. };
  756. const loadChannels = async (startIdx, pageSize, idSort, enableTagMode) => {
  757. setLoading(true);
  758. const res = await API.get(
  759. `/api/channel/?p=${startIdx}&page_size=${pageSize}&id_sort=${idSort}&tag_mode=${enableTagMode}`
  760. );
  761. if (res === undefined) {
  762. return;
  763. }
  764. const { success, message, data } = res.data;
  765. if (success) {
  766. if (startIdx === 0) {
  767. setChannelFormat(data, enableTagMode);
  768. } else {
  769. let newChannels = [...channels];
  770. newChannels.splice(startIdx * pageSize, data.length, ...data);
  771. setChannelFormat(newChannels, enableTagMode);
  772. }
  773. } else {
  774. showError(message);
  775. }
  776. setLoading(false);
  777. };
  778. const copySelectedChannel = async (record) => {
  779. const channelToCopy = record
  780. channelToCopy.name += t('_复制');
  781. channelToCopy.created_time = null;
  782. channelToCopy.balance = 0;
  783. channelToCopy.used_quota = 0;
  784. if (!channelToCopy) {
  785. showError(t('渠道未找到,请刷新页面后重试。'));
  786. return;
  787. }
  788. try {
  789. const newChannel = { ...channelToCopy, id: undefined };
  790. const response = await API.post('/api/channel/', newChannel);
  791. if (response.data.success) {
  792. showSuccess(t('渠道复制成功'));
  793. await refresh();
  794. } else {
  795. showError(response.data.message);
  796. }
  797. } catch (error) {
  798. showError(t('渠道复制失败: ') + error.message);
  799. }
  800. };
  801. const refresh = async () => {
  802. await loadChannels(activePage - 1, pageSize, idSort, enableTagMode);
  803. };
  804. useEffect(() => {
  805. // console.log('default effect')
  806. const localIdSort = localStorage.getItem('id-sort') === 'true';
  807. const localPageSize =
  808. parseInt(localStorage.getItem('page-size')) || ITEMS_PER_PAGE;
  809. setIdSort(localIdSort);
  810. setPageSize(localPageSize);
  811. loadChannels(0, localPageSize, localIdSort, enableTagMode)
  812. .then()
  813. .catch((reason) => {
  814. showError(reason);
  815. });
  816. fetchGroups().then();
  817. loadChannelModels().then();
  818. }, []);
  819. const manageChannel = async (id, action, record, value) => {
  820. let data = { id };
  821. let res;
  822. switch (action) {
  823. case 'delete':
  824. res = await API.delete(`/api/channel/${id}/`);
  825. break;
  826. case 'enable':
  827. data.status = 1;
  828. res = await API.put('/api/channel/', data);
  829. break;
  830. case 'disable':
  831. data.status = 2;
  832. res = await API.put('/api/channel/', data);
  833. break;
  834. case 'priority':
  835. if (value === '') {
  836. return;
  837. }
  838. data.priority = parseInt(value);
  839. res = await API.put('/api/channel/', data);
  840. break;
  841. case 'weight':
  842. if (value === '') {
  843. return;
  844. }
  845. data.weight = parseInt(value);
  846. if (data.weight < 0) {
  847. data.weight = 0;
  848. }
  849. res = await API.put('/api/channel/', data);
  850. break;
  851. }
  852. const { success, message } = res.data;
  853. if (success) {
  854. showSuccess(t('操作成功完成!'));
  855. let channel = res.data.data;
  856. let newChannels = [...channels];
  857. if (action === 'delete') {
  858. } else {
  859. record.status = channel.status;
  860. }
  861. setChannels(newChannels);
  862. } else {
  863. showError(message);
  864. }
  865. };
  866. const manageTag = async (tag, action) => {
  867. console.log(tag, action);
  868. let res;
  869. switch (action) {
  870. case 'enable':
  871. res = await API.post('/api/channel/tag/enabled', {
  872. tag: tag
  873. });
  874. break;
  875. case 'disable':
  876. res = await API.post('/api/channel/tag/disabled', {
  877. tag: tag
  878. });
  879. break;
  880. }
  881. const { success, message } = res.data;
  882. if (success) {
  883. showSuccess('操作成功完成!');
  884. let newChannels = [...channels];
  885. for (let i = 0; i < newChannels.length; i++) {
  886. if (newChannels[i].tag === tag) {
  887. let status = action === 'enable' ? 1 : 2;
  888. newChannels[i]?.children?.forEach((channel) => {
  889. channel.status = status;
  890. });
  891. newChannels[i].status = status;
  892. }
  893. }
  894. setChannels(newChannels);
  895. } else {
  896. showError(message);
  897. }
  898. };
  899. const searchChannels = async (searchKeyword, searchGroup, searchModel, enableTagMode) => {
  900. if (searchKeyword === '' && searchGroup === '' && searchModel === '') {
  901. await loadChannels(0, pageSize, idSort, enableTagMode);
  902. setActivePage(1);
  903. return;
  904. }
  905. setSearching(true);
  906. const res = await API.get(
  907. `/api/channel/search?keyword=${searchKeyword}&group=${searchGroup}&model=${searchModel}&id_sort=${idSort}&tag_mode=${enableTagMode}`
  908. );
  909. const { success, message, data } = res.data;
  910. if (success) {
  911. setChannelFormat(data, enableTagMode);
  912. setActivePage(1);
  913. } else {
  914. showError(message);
  915. }
  916. setSearching(false);
  917. };
  918. const updateChannelProperty = (channelId, updateFn) => {
  919. // Create a new copy of channels array
  920. const newChannels = [...channels];
  921. let updated = false;
  922. // Find and update the correct channel
  923. newChannels.forEach(channel => {
  924. if (channel.children !== undefined) {
  925. // If this is a tag group, search in its children
  926. channel.children.forEach(child => {
  927. if (child.id === channelId) {
  928. updateFn(child);
  929. updated = true;
  930. }
  931. });
  932. } else if (channel.id === channelId) {
  933. // Direct channel match
  934. updateFn(channel);
  935. updated = true;
  936. }
  937. });
  938. // Only update state if we actually modified a channel
  939. if (updated) {
  940. setChannels(newChannels);
  941. }
  942. };
  943. const testChannel = async (record, model) => {
  944. const res = await API.get(`/api/channel/test/${record.id}?model=${model}`);
  945. const { success, message, time } = res.data;
  946. if (success) {
  947. // Also update the channels state to persist the change
  948. updateChannelProperty(record.id, (channel) => {
  949. channel.response_time = time * 1000;
  950. channel.test_time = Date.now() / 1000;
  951. });
  952. showInfo(t('通道 ${name} 测试成功,耗时 ${time.toFixed(2)} 秒。').replace('${name}', record.name).replace('${time.toFixed(2)}', time.toFixed(2)));
  953. } else {
  954. showError(message);
  955. }
  956. };
  957. const updateChannelBalance = async (record) => {
  958. const res = await API.get(`/api/channel/update_balance/${record.id}/`);
  959. const { success, message, balance } = res.data;
  960. if (success) {
  961. updateChannelProperty(record.id, (channel) => {
  962. channel.balance = balance;
  963. channel.balance_updated_time = Date.now() / 1000;
  964. });
  965. showInfo(t('通道 ${name} 余额更新成功!').replace('${name}', record.name));
  966. } else {
  967. showError(message);
  968. }
  969. };
  970. const testAllChannels = async () => {
  971. const res = await API.get(`/api/channel/test`);
  972. const { success, message } = res.data;
  973. if (success) {
  974. showInfo(t('已成功开始测试所有已启用通道,请刷新页面查看结果。'));
  975. } else {
  976. showError(message);
  977. }
  978. };
  979. const deleteAllDisabledChannels = async () => {
  980. const res = await API.delete(`/api/channel/disabled`);
  981. const { success, message, data } = res.data;
  982. if (success) {
  983. showSuccess(t('已删除所有禁用渠道,共计 ${data} 个').replace('${data}', data));
  984. await refresh();
  985. } else {
  986. showError(message);
  987. }
  988. };
  989. const updateAllChannelsBalance = async () => {
  990. setUpdatingBalance(true);
  991. const res = await API.get(`/api/channel/update_balance`);
  992. const { success, message } = res.data;
  993. if (success) {
  994. showInfo(t('已更新完毕所有已启用通道余额!'));
  995. } else {
  996. showError(message);
  997. }
  998. setUpdatingBalance(false);
  999. };
  1000. const batchDeleteChannels = async () => {
  1001. if (selectedChannels.length === 0) {
  1002. showError(t('请先选择要删除的通道!'));
  1003. return;
  1004. }
  1005. setLoading(true);
  1006. let ids = [];
  1007. selectedChannels.forEach((channel) => {
  1008. ids.push(channel.id);
  1009. });
  1010. const res = await API.post(`/api/channel/batch`, { ids: ids });
  1011. const { success, message, data } = res.data;
  1012. if (success) {
  1013. showSuccess(t('已删除 ${data} 个通道!').replace('${data}', data));
  1014. await refresh();
  1015. } else {
  1016. showError(message);
  1017. }
  1018. setLoading(false);
  1019. };
  1020. const fixChannelsAbilities = async () => {
  1021. const res = await API.post(`/api/channel/fix`);
  1022. const { success, message, data } = res.data;
  1023. if (success) {
  1024. showSuccess(t('已修复 ${data} 个通道!').replace('${data}', data));
  1025. await refresh();
  1026. } else {
  1027. showError(message);
  1028. }
  1029. };
  1030. let pageData = channels.slice(
  1031. (activePage - 1) * pageSize,
  1032. activePage * pageSize
  1033. );
  1034. const handlePageChange = (page) => {
  1035. setActivePage(page);
  1036. if (page === Math.ceil(channels.length / pageSize) + 1) {
  1037. // In this case we have to load more data and then append them.
  1038. loadChannels(page - 1, pageSize, idSort, enableTagMode).then((r) => {
  1039. });
  1040. }
  1041. };
  1042. const handlePageSizeChange = async (size) => {
  1043. localStorage.setItem('page-size', size + '');
  1044. setPageSize(size);
  1045. setActivePage(1);
  1046. loadChannels(0, size, idSort, enableTagMode)
  1047. .then()
  1048. .catch((reason) => {
  1049. showError(reason);
  1050. });
  1051. };
  1052. const fetchGroups = async () => {
  1053. try {
  1054. let res = await API.get(`/api/group/`);
  1055. // add 'all' option
  1056. // res.data.data.unshift('all');
  1057. if (res === undefined) {
  1058. return;
  1059. }
  1060. setGroupOptions(
  1061. res.data.data.map((group) => ({
  1062. label: group,
  1063. value: group
  1064. }))
  1065. );
  1066. } catch (error) {
  1067. showError(error.message);
  1068. }
  1069. };
  1070. const submitTagEdit = async (type, data) => {
  1071. switch (type) {
  1072. case 'priority':
  1073. if (data.priority === undefined || data.priority === '') {
  1074. showInfo('优先级必须是整数!');
  1075. return;
  1076. }
  1077. data.priority = parseInt(data.priority);
  1078. break;
  1079. case 'weight':
  1080. if (data.weight === undefined || data.weight < 0 || data.weight === '') {
  1081. showInfo('权重必须是非负整数!');
  1082. return;
  1083. }
  1084. data.weight = parseInt(data.weight);
  1085. break
  1086. }
  1087. try {
  1088. const res = await API.put('/api/channel/tag', data);
  1089. if (res?.data?.success) {
  1090. showSuccess('更新成功!');
  1091. await refresh();
  1092. }
  1093. } catch (error) {
  1094. showError(error);
  1095. }
  1096. }
  1097. const closeEdit = () => {
  1098. setShowEdit(false);
  1099. };
  1100. const handleRow = (record, index) => {
  1101. if (record.status !== 1) {
  1102. return {
  1103. style: {
  1104. background: 'var(--semi-color-disabled-border)'
  1105. }
  1106. };
  1107. } else {
  1108. return {};
  1109. }
  1110. };
  1111. const batchSetChannelTag = async () => {
  1112. if (selectedChannels.length === 0) {
  1113. showError(t('请先选择要设置标签的渠道!'));
  1114. return;
  1115. }
  1116. if (batchSetTagValue === '') {
  1117. showError(t('标签不能为空!'));
  1118. return;
  1119. }
  1120. let ids = selectedChannels.map(channel => channel.id);
  1121. const res = await API.post('/api/channel/batch/tag', {
  1122. ids: ids,
  1123. tag: batchSetTagValue === '' ? null : batchSetTagValue
  1124. });
  1125. if (res.data.success) {
  1126. showSuccess(t('已为 ${count} 个渠道设置标签!').replace('${count}', res.data.data));
  1127. await refresh();
  1128. setShowBatchSetTag(false);
  1129. } else {
  1130. showError(res.data.message);
  1131. }
  1132. };
  1133. return (
  1134. <>
  1135. {renderColumnSelector()}
  1136. <EditTagModal
  1137. visible={showEditTag}
  1138. tag={editingTag}
  1139. handleClose={() => setShowEditTag(false)}
  1140. refresh={refresh}
  1141. />
  1142. <EditChannel
  1143. refresh={refresh}
  1144. visible={showEdit}
  1145. handleClose={closeEdit}
  1146. editingChannel={editingChannel}
  1147. />
  1148. <Form
  1149. onSubmit={() => {
  1150. searchChannels(searchKeyword, searchGroup, searchModel, enableTagMode);
  1151. }}
  1152. labelPosition="left"
  1153. >
  1154. <div style={{ display: 'flex' }}>
  1155. <Space>
  1156. <Form.Input
  1157. field="search_keyword"
  1158. label={t('搜索渠道关键词')}
  1159. placeholder={t('搜索渠道的 ID,名称和密钥 ...')}
  1160. value={searchKeyword}
  1161. loading={searching}
  1162. onChange={(v) => {
  1163. setSearchKeyword(v.trim());
  1164. }}
  1165. />
  1166. <Form.Input
  1167. field="search_model"
  1168. label={t('模型')}
  1169. placeholder={t('模型关键字')}
  1170. value={searchModel}
  1171. loading={searching}
  1172. onChange={(v) => {
  1173. setSearchModel(v.trim());
  1174. }}
  1175. />
  1176. <Form.Select
  1177. field="group"
  1178. label={t('分组')}
  1179. optionList={[{ label: t('选择分组'), value: null }, ...groupOptions]}
  1180. initValue={null}
  1181. onChange={(v) => {
  1182. setSearchGroup(v);
  1183. searchChannels(searchKeyword, v, searchModel, enableTagMode);
  1184. }}
  1185. />
  1186. <Button
  1187. label={t('查询')}
  1188. type="primary"
  1189. htmlType="submit"
  1190. className="btn-margin-right"
  1191. style={{ marginRight: 8 }}
  1192. >
  1193. {t('查询')}
  1194. </Button>
  1195. </Space>
  1196. </div>
  1197. </Form>
  1198. <Divider style={{ marginBottom: 15 }} />
  1199. <div
  1200. style={{
  1201. display: 'flex',
  1202. flexDirection: isMobile() ? 'column' : 'row',
  1203. marginTop: isMobile() ? 0 : -45,
  1204. zIndex: 999,
  1205. pointerEvents: 'none'
  1206. }}
  1207. >
  1208. <Space
  1209. style={{
  1210. pointerEvents: 'auto',
  1211. marginTop: isMobile() ? 0 : 45,
  1212. marginBottom: isMobile() ? 16 : 0,
  1213. display: 'flex',
  1214. flexWrap: isMobile() ? 'wrap' : 'nowrap',
  1215. gap: '8px'
  1216. }}
  1217. >
  1218. <div style={{
  1219. display: 'flex',
  1220. alignItems: 'center',
  1221. marginRight: 16,
  1222. flexWrap: 'nowrap'
  1223. }}>
  1224. <Typography.Text strong style={{ marginRight: 8 }}>{t('使用ID排序')}</Typography.Text>
  1225. <Switch
  1226. checked={idSort}
  1227. label={t('使用ID排序')}
  1228. uncheckedText={t('关')}
  1229. aria-label={t('是否用ID排序')}
  1230. onChange={(v) => {
  1231. localStorage.setItem('id-sort', v + '');
  1232. setIdSort(v);
  1233. loadChannels(0, pageSize, v, enableTagMode)
  1234. .then()
  1235. .catch((reason) => {
  1236. showError(reason);
  1237. });
  1238. }}
  1239. ></Switch>
  1240. </div>
  1241. <div style={{
  1242. display: 'flex',
  1243. flexWrap: 'wrap',
  1244. gap: '8px'
  1245. }}>
  1246. <Button
  1247. theme="light"
  1248. type="primary"
  1249. icon={<IconPlus />}
  1250. onClick={() => {
  1251. setEditingChannel({
  1252. id: undefined
  1253. });
  1254. setShowEdit(true);
  1255. }}
  1256. >
  1257. {t('添加渠道')}
  1258. </Button>
  1259. <Button
  1260. theme="light"
  1261. type="primary"
  1262. icon={<IconRefresh />}
  1263. onClick={refresh}
  1264. >
  1265. {t('刷新')}
  1266. </Button>
  1267. <Dropdown
  1268. trigger="click"
  1269. render={
  1270. <Dropdown.Menu>
  1271. <Dropdown.Item>
  1272. <Popconfirm
  1273. title={t('确定?')}
  1274. okType={'warning'}
  1275. onConfirm={testAllChannels}
  1276. position={isMobile() ? 'top' : 'top'}
  1277. >
  1278. <Button theme="light" type="warning" style={{ width: '100%' }}>
  1279. {t('测试所有通道')}
  1280. </Button>
  1281. </Popconfirm>
  1282. </Dropdown.Item>
  1283. <Dropdown.Item>
  1284. <Popconfirm
  1285. title={t('确定?')}
  1286. okType={'secondary'}
  1287. onConfirm={updateAllChannelsBalance}
  1288. >
  1289. <Button theme="light" type="secondary" style={{ width: '100%' }}>
  1290. {t('更新所有已启用通道余额')}
  1291. </Button>
  1292. </Popconfirm>
  1293. </Dropdown.Item>
  1294. <Dropdown.Item>
  1295. <Popconfirm
  1296. title={t('确定是否要删除禁用通道?')}
  1297. content={t('此修改将不可逆')}
  1298. okType={'danger'}
  1299. onConfirm={deleteAllDisabledChannels}
  1300. >
  1301. <Button theme="light" type="danger" style={{ width: '100%' }}>
  1302. {t('删除禁用通道')}
  1303. </Button>
  1304. </Popconfirm>
  1305. </Dropdown.Item>
  1306. </Dropdown.Menu>
  1307. }
  1308. >
  1309. <Button theme="light" type="tertiary" icon={<IconSetting />}>
  1310. {t('批量操作')}
  1311. </Button>
  1312. </Dropdown>
  1313. </div>
  1314. </Space>
  1315. </div>
  1316. <div style={{
  1317. marginTop: 20,
  1318. display: 'flex',
  1319. flexDirection: isMobile() ? 'column' : 'row',
  1320. alignItems: isMobile() ? 'flex-start' : 'center',
  1321. gap: isMobile() ? '8px' : '16px'
  1322. }}>
  1323. <div style={{
  1324. display: 'flex',
  1325. alignItems: 'center',
  1326. marginBottom: isMobile() ? 8 : 0
  1327. }}>
  1328. <Typography.Text strong style={{ marginRight: 8 }}>{t('开启批量操作')}</Typography.Text>
  1329. <Switch
  1330. label={t('开启批量操作')}
  1331. uncheckedText={t('关')}
  1332. aria-label={t('是否开启批量操作')}
  1333. onChange={(v) => {
  1334. setEnableBatchDelete(v);
  1335. }}
  1336. />
  1337. </div>
  1338. <div style={{
  1339. display: 'flex',
  1340. flexWrap: 'wrap',
  1341. gap: '8px'
  1342. }}>
  1343. <Popconfirm
  1344. title={t('确定是否要删除所选通道?')}
  1345. content={t('此修改将不可逆')}
  1346. okType={'danger'}
  1347. onConfirm={batchDeleteChannels}
  1348. disabled={!enableBatchDelete}
  1349. >
  1350. <Button
  1351. disabled={!enableBatchDelete}
  1352. theme="light"
  1353. type="danger"
  1354. >
  1355. {t('删除所选通道')}
  1356. </Button>
  1357. </Popconfirm>
  1358. <Popconfirm
  1359. title={t('确定是否要修复数据库一致性?')}
  1360. content={t('进行该操作时,可能导致渠道访问错误,请仅在数据库出现问题时使用')}
  1361. okType={'warning'}
  1362. onConfirm={fixChannelsAbilities}
  1363. >
  1364. <Button theme="light" type="secondary">
  1365. {t('修复数据库一致性')}
  1366. </Button>
  1367. </Popconfirm>
  1368. </div>
  1369. </div>
  1370. <div style={{
  1371. marginTop: 20,
  1372. display: 'flex',
  1373. flexDirection: isMobile() ? 'column' : 'row',
  1374. alignItems: isMobile() ? 'flex-start' : 'center',
  1375. gap: isMobile() ? '8px' : '16px'
  1376. }}>
  1377. <div style={{
  1378. display: 'flex',
  1379. alignItems: 'center',
  1380. marginBottom: isMobile() ? 8 : 0
  1381. }}>
  1382. <Typography.Text strong style={{ marginRight: 8 }}>{t('标签聚合模式')}</Typography.Text>
  1383. <Switch
  1384. checked={enableTagMode}
  1385. label={t('标签聚合模式')}
  1386. uncheckedText={t('关')}
  1387. aria-label={t('是否启用标签聚合')}
  1388. onChange={(v) => {
  1389. setEnableTagMode(v);
  1390. loadChannels(0, pageSize, idSort, v);
  1391. }}
  1392. />
  1393. </div>
  1394. <div style={{
  1395. display: 'flex',
  1396. flexWrap: 'wrap',
  1397. gap: '8px'
  1398. }}>
  1399. <Button
  1400. disabled={!enableBatchDelete}
  1401. theme="light"
  1402. type="primary"
  1403. onClick={() => setShowBatchSetTag(true)}
  1404. >
  1405. {t('批量设置标签')}
  1406. </Button>
  1407. <Button
  1408. theme="light"
  1409. type="tertiary"
  1410. icon={<IconSetting />}
  1411. onClick={() => setShowColumnSelector(true)}
  1412. >
  1413. {t('列设置')}
  1414. </Button>
  1415. </div>
  1416. </div>
  1417. <Table
  1418. loading={loading}
  1419. columns={getVisibleColumns()}
  1420. dataSource={pageData}
  1421. pagination={{
  1422. currentPage: activePage,
  1423. pageSize: pageSize,
  1424. total: channelCount,
  1425. pageSizeOpts: [10, 20, 50, 100],
  1426. showSizeChanger: true,
  1427. formatPageText: (page) => '',
  1428. onPageSizeChange: (size) => {
  1429. handlePageSizeChange(size).then();
  1430. },
  1431. onPageChange: handlePageChange
  1432. }}
  1433. expandAllRows={false}
  1434. onRow={handleRow}
  1435. rowSelection={
  1436. enableBatchDelete
  1437. ? {
  1438. onChange: (selectedRowKeys, selectedRows) => {
  1439. // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  1440. setSelectedChannels(selectedRows);
  1441. }
  1442. }
  1443. : null
  1444. }
  1445. />
  1446. <Modal
  1447. title={t('批量设置标签')}
  1448. visible={showBatchSetTag}
  1449. onOk={batchSetChannelTag}
  1450. onCancel={() => setShowBatchSetTag(false)}
  1451. maskClosable={false}
  1452. centered={true}
  1453. style={{ width: isMobile() ? '90%' : 500 }}
  1454. >
  1455. <div style={{ marginBottom: 20 }}>
  1456. <Typography.Text>{t('请输入要设置的标签名称')}</Typography.Text>
  1457. </div>
  1458. <Input
  1459. placeholder={t('请输入标签名称')}
  1460. value={batchSetTagValue}
  1461. onChange={(v) => setBatchSetTagValue(v)}
  1462. size="large"
  1463. />
  1464. <div style={{ marginTop: 16 }}>
  1465. <Typography.Text type="secondary">
  1466. {t('已选择 ${count} 个渠道').replace('${count}', selectedChannels.length)}
  1467. </Typography.Text>
  1468. </div>
  1469. </Modal>
  1470. {/* 模型测试弹窗 */}
  1471. <Modal
  1472. title={t('选择模型进行测试')}
  1473. visible={showModelTestModal && currentTestChannel !== null}
  1474. onCancel={() => {
  1475. setShowModelTestModal(false);
  1476. setModelSearchKeyword('');
  1477. }}
  1478. footer={null}
  1479. maskClosable={true}
  1480. centered={true}
  1481. >
  1482. <div style={{ maxHeight: '500px', overflowY: 'auto', padding: '10px' }}>
  1483. {currentTestChannel && (
  1484. <div>
  1485. <Typography.Title heading={6} style={{ marginBottom: '16px' }}>
  1486. {t('渠道')}: {currentTestChannel.name}
  1487. </Typography.Title>
  1488. {/* 搜索框 */}
  1489. <Input
  1490. placeholder={t('搜索模型...')}
  1491. value={modelSearchKeyword}
  1492. onChange={(v) => setModelSearchKeyword(v)}
  1493. style={{ marginBottom: '16px' }}
  1494. prefix={<IconFilter />}
  1495. showClear
  1496. />
  1497. <div style={{
  1498. display: 'grid',
  1499. gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))',
  1500. gap: '10px'
  1501. }}>
  1502. {currentTestChannel.models.split(',')
  1503. .filter(model => model.toLowerCase().includes(modelSearchKeyword.toLowerCase()))
  1504. .map((model, index) => {
  1505. return (
  1506. <Button
  1507. key={index}
  1508. theme="light"
  1509. type="tertiary"
  1510. style={{
  1511. height: 'auto',
  1512. padding: '8px 12px',
  1513. textAlign: 'center',
  1514. }}
  1515. onClick={() => {
  1516. testChannel(currentTestChannel, model);
  1517. }}
  1518. >
  1519. {model}
  1520. </Button>
  1521. );
  1522. })}
  1523. </div>
  1524. {/* 显示搜索结果数量 */}
  1525. {modelSearchKeyword && (
  1526. <Typography.Text type="secondary" style={{ marginTop: '16px', display: 'block' }}>
  1527. {t('找到')} {currentTestChannel.models.split(',').filter(model =>
  1528. model.toLowerCase().includes(modelSearchKeyword.toLowerCase())
  1529. ).length} {t('个模型')}
  1530. </Typography.Text>
  1531. )}
  1532. </div>
  1533. )}
  1534. </div>
  1535. </Modal>
  1536. </>
  1537. );
  1538. };
  1539. export default ChannelsTable;