ChannelsTable.js 50 KB

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