ChannelsTable.js 48 KB

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