ChannelsTable.js 63 KB

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