| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079 |
- import React, { useEffect, useState, useMemo, useRef } from 'react';
- import {
- API,
- showError,
- showInfo,
- showSuccess,
- timestamp2string,
- renderGroup,
- renderQuota,
- getChannelIcon,
- renderQuotaWithAmount
- } from '../../helpers/index.js';
- import {
- CheckCircle,
- XCircle,
- AlertCircle,
- HelpCircle,
- Coins,
- Tags,
- } from 'lucide-react';
- import { CHANNEL_OPTIONS, ITEMS_PER_PAGE } from '../../constants/index.js';
- import {
- Button,
- Divider,
- Dropdown,
- Empty,
- Input,
- InputNumber,
- Modal,
- Space,
- SplitButtonGroup,
- Switch,
- Table,
- Tag,
- Tooltip,
- Typography,
- Checkbox,
- Card,
- Form,
- Tabs,
- TabPane,
- Select,
- } from '@douyinfe/semi-ui';
- import {
- IllustrationNoResult,
- IllustrationNoResultDark
- } from '@douyinfe/semi-illustrations';
- import EditChannel from '../../pages/Channel/EditChannel.js';
- import {
- IconTreeTriangleDown,
- IconPlus,
- IconRefresh,
- IconSetting,
- IconDescend,
- IconSearch,
- IconEdit,
- IconDelete,
- IconStop,
- IconPlay,
- IconMore,
- IconCopy,
- IconSmallTriangleRight
- } from '@douyinfe/semi-icons';
- import { loadChannelModels } from '../../helpers/index.js';
- import EditTagModal from '../../pages/Channel/EditTagModal.js';
- import { useTranslation } from 'react-i18next';
- import { useTableCompactMode } from '../../hooks/useTableCompactMode';
- const ChannelsTable = () => {
- const { t } = useTranslation();
- let type2label = undefined;
- const renderType = (type) => {
- if (!type2label) {
- type2label = new Map();
- for (let i = 0; i < CHANNEL_OPTIONS.length; i++) {
- type2label[CHANNEL_OPTIONS[i].value] = CHANNEL_OPTIONS[i];
- }
- type2label[0] = { value: 0, label: t('未知类型'), color: 'grey' };
- }
- return (
- <Tag
- size='large'
- color={type2label[type]?.color}
- shape='circle'
- prefixIcon={getChannelIcon(type)}
- >
- {type2label[type]?.label}
- </Tag>
- );
- };
- const renderTagType = () => {
- return (
- <Tag
- color='light-blue'
- prefixIcon={<Tags size={14} />}
- size='large'
- shape='circle'
- type='light'
- >
- {t('标签聚合')}
- </Tag>
- );
- };
- const renderStatus = (status) => {
- switch (status) {
- case 1:
- return (
- <Tag size='large' color='green' shape='circle' prefixIcon={<CheckCircle size={14} />}>
- {t('已启用')}
- </Tag>
- );
- case 2:
- return (
- <Tag size='large' color='red' shape='circle' prefixIcon={<XCircle size={14} />}>
- {t('已禁用')}
- </Tag>
- );
- case 3:
- return (
- <Tag size='large' color='yellow' shape='circle' prefixIcon={<AlertCircle size={14} />}>
- {t('自动禁用')}
- </Tag>
- );
- default:
- return (
- <Tag size='large' color='grey' shape='circle' prefixIcon={<HelpCircle size={14} />}>
- {t('未知状态')}
- </Tag>
- );
- }
- };
- const renderResponseTime = (responseTime) => {
- let time = responseTime / 1000;
- time = time.toFixed(2) + t(' 秒');
- if (responseTime === 0) {
- return (
- <Tag size='large' color='grey' shape='circle'>
- {t('未测试')}
- </Tag>
- );
- } else if (responseTime <= 1000) {
- return (
- <Tag size='large' color='green' shape='circle'>
- {time}
- </Tag>
- );
- } else if (responseTime <= 3000) {
- return (
- <Tag size='large' color='lime' shape='circle'>
- {time}
- </Tag>
- );
- } else if (responseTime <= 5000) {
- return (
- <Tag size='large' color='yellow' shape='circle'>
- {time}
- </Tag>
- );
- } else {
- return (
- <Tag size='large' color='red' shape='circle'>
- {time}
- </Tag>
- );
- }
- };
- // Define column keys for selection
- const COLUMN_KEYS = {
- ID: 'id',
- NAME: 'name',
- GROUP: 'group',
- TYPE: 'type',
- STATUS: 'status',
- RESPONSE_TIME: 'response_time',
- BALANCE: 'balance',
- PRIORITY: 'priority',
- WEIGHT: 'weight',
- OPERATE: 'operate',
- };
- // State for column visibility
- const [visibleColumns, setVisibleColumns] = useState({});
- const [showColumnSelector, setShowColumnSelector] = useState(false);
- // 状态筛选 all / enabled / disabled
- const [statusFilter, setStatusFilter] = useState(
- localStorage.getItem('channel-status-filter') || 'all'
- );
- // Load saved column preferences from localStorage
- useEffect(() => {
- const savedColumns = localStorage.getItem('channels-table-columns');
- if (savedColumns) {
- try {
- const parsed = JSON.parse(savedColumns);
- // Make sure all columns are accounted for
- const defaults = getDefaultColumnVisibility();
- const merged = { ...defaults, ...parsed };
- setVisibleColumns(merged);
- } catch (e) {
- console.error('Failed to parse saved column preferences', e);
- initDefaultColumns();
- }
- } else {
- initDefaultColumns();
- }
- }, []);
- // Update table when column visibility changes
- useEffect(() => {
- if (Object.keys(visibleColumns).length > 0) {
- // Save to localStorage
- localStorage.setItem(
- 'channels-table-columns',
- JSON.stringify(visibleColumns),
- );
- }
- }, [visibleColumns]);
- // Get default column visibility
- const getDefaultColumnVisibility = () => {
- return {
- [COLUMN_KEYS.ID]: true,
- [COLUMN_KEYS.NAME]: true,
- [COLUMN_KEYS.GROUP]: true,
- [COLUMN_KEYS.TYPE]: true,
- [COLUMN_KEYS.STATUS]: true,
- [COLUMN_KEYS.RESPONSE_TIME]: true,
- [COLUMN_KEYS.BALANCE]: true,
- [COLUMN_KEYS.PRIORITY]: true,
- [COLUMN_KEYS.WEIGHT]: true,
- [COLUMN_KEYS.OPERATE]: true,
- };
- };
- // Initialize default column visibility
- const initDefaultColumns = () => {
- const defaults = getDefaultColumnVisibility();
- setVisibleColumns(defaults);
- };
- // Handle column visibility change
- const handleColumnVisibilityChange = (columnKey, checked) => {
- const updatedColumns = { ...visibleColumns, [columnKey]: checked };
- setVisibleColumns(updatedColumns);
- };
- // Handle "Select All" checkbox
- const handleSelectAll = (checked) => {
- const allKeys = Object.keys(COLUMN_KEYS).map((key) => COLUMN_KEYS[key]);
- const updatedColumns = {};
- allKeys.forEach((key) => {
- updatedColumns[key] = checked;
- });
- setVisibleColumns(updatedColumns);
- };
- // Define all columns with keys
- const allColumns = [
- {
- key: COLUMN_KEYS.ID,
- title: t('ID'),
- dataIndex: 'id',
- },
- {
- key: COLUMN_KEYS.NAME,
- title: t('名称'),
- dataIndex: 'name',
- },
- {
- key: COLUMN_KEYS.GROUP,
- title: t('分组'),
- dataIndex: 'group',
- render: (text, record, index) => (
- <div>
- <Space spacing={2}>
- {text
- ?.split(',')
- .sort((a, b) => {
- if (a === 'default') return -1;
- if (b === 'default') return 1;
- return a.localeCompare(b);
- })
- .map((item, index) => renderGroup(item))}
- </Space>
- </div>
- ),
- },
- {
- key: COLUMN_KEYS.TYPE,
- title: t('类型'),
- dataIndex: 'type',
- render: (text, record, index) => {
- if (record.children === undefined) {
- return <>{renderType(text)}</>;
- } else {
- return <>{renderTagType()}</>;
- }
- },
- },
- {
- key: COLUMN_KEYS.STATUS,
- title: t('状态'),
- dataIndex: 'status',
- render: (text, record, index) => {
- if (text === 3) {
- if (record.other_info === '') {
- record.other_info = '{}';
- }
- let otherInfo = JSON.parse(record.other_info);
- let reason = otherInfo['status_reason'];
- let time = otherInfo['status_time'];
- return (
- <div>
- <Tooltip
- content={t('原因:') + reason + t(',时间:') + timestamp2string(time)}
- >
- {renderStatus(text)}
- </Tooltip>
- </div>
- );
- } else {
- return renderStatus(text);
- }
- },
- },
- {
- key: COLUMN_KEYS.RESPONSE_TIME,
- title: t('响应时间'),
- dataIndex: 'response_time',
- render: (text, record, index) => (
- <div>{renderResponseTime(text)}</div>
- ),
- },
- {
- key: COLUMN_KEYS.BALANCE,
- title: t('已用/剩余'),
- dataIndex: 'expired_time',
- render: (text, record, index) => {
- if (record.children === undefined) {
- return (
- <div>
- <Space spacing={1}>
- <Tooltip content={t('已用额度')}>
- <Tag color='white' type='ghost' size='large' shape='circle' prefixIcon={<Coins size={14} />}>
- {renderQuota(record.used_quota)}
- </Tag>
- </Tooltip>
- <Tooltip content={t('剩余额度$') + record.balance + t(',点击更新')}>
- <Tag
- color='white'
- type='ghost'
- size='large'
- shape='circle'
- prefixIcon={<Coins size={14} />}
- onClick={() => updateChannelBalance(record)}
- >
- {renderQuotaWithAmount(record.balance)}
- </Tag>
- </Tooltip>
- </Space>
- </div>
- );
- } else {
- return (
- <Tooltip content={t('已用额度')}>
- <Tag color='white' type='ghost' size='large' shape='circle' prefixIcon={<Coins size={14} />}>
- {renderQuota(record.used_quota)}
- </Tag>
- </Tooltip>
- );
- }
- },
- },
- {
- key: COLUMN_KEYS.PRIORITY,
- title: t('优先级'),
- dataIndex: 'priority',
- render: (text, record, index) => {
- if (record.children === undefined) {
- return (
- <div>
- <InputNumber
- style={{ width: 70 }}
- name='priority'
- onBlur={(e) => {
- manageChannel(record.id, 'priority', record, e.target.value);
- }}
- keepFocus={true}
- innerButtons
- defaultValue={record.priority}
- min={-999}
- size="small"
- />
- </div>
- );
- } else {
- return (
- <InputNumber
- style={{ width: 70 }}
- name='priority'
- keepFocus={true}
- onBlur={(e) => {
- Modal.warning({
- title: t('修改子渠道优先级'),
- content: t('确定要修改所有子渠道优先级为 ') + e.target.value + t(' 吗?'),
- onOk: () => {
- if (e.target.value === '') {
- return;
- }
- submitTagEdit('priority', {
- tag: record.key,
- priority: e.target.value,
- });
- },
- });
- }}
- innerButtons
- defaultValue={record.priority}
- min={-999}
- size="small"
- />
- );
- }
- },
- },
- {
- key: COLUMN_KEYS.WEIGHT,
- title: t('权重'),
- dataIndex: 'weight',
- render: (text, record, index) => {
- if (record.children === undefined) {
- return (
- <div>
- <InputNumber
- style={{ width: 70 }}
- name='weight'
- onBlur={(e) => {
- manageChannel(record.id, 'weight', record, e.target.value);
- }}
- keepFocus={true}
- innerButtons
- defaultValue={record.weight}
- min={0}
- size="small"
- />
- </div>
- );
- } else {
- return (
- <InputNumber
- style={{ width: 70 }}
- name='weight'
- keepFocus={true}
- onBlur={(e) => {
- Modal.warning({
- title: t('修改子渠道权重'),
- content: t('确定要修改所有子渠道权重为 ') + e.target.value + t(' 吗?'),
- onOk: () => {
- if (e.target.value === '') {
- return;
- }
- submitTagEdit('weight', {
- tag: record.key,
- weight: e.target.value,
- });
- },
- });
- }}
- innerButtons
- defaultValue={record.weight}
- min={-999}
- size="small"
- />
- );
- }
- },
- },
- {
- key: COLUMN_KEYS.OPERATE,
- title: '',
- dataIndex: 'operate',
- fixed: 'right',
- render: (text, record, index) => {
- if (record.children === undefined) {
- // 创建更多操作的下拉菜单项
- const moreMenuItems = [
- {
- node: 'item',
- name: t('删除'),
- icon: <IconDelete />,
- type: 'danger',
- onClick: () => {
- Modal.confirm({
- title: t('确定是否要删除此渠道?'),
- content: t('此修改将不可逆'),
- onOk: () => {
- manageChannel(record.id, 'delete', record).then(() => {
- removeRecord(record);
- });
- },
- });
- },
- },
- {
- node: 'item',
- name: t('复制'),
- icon: <IconCopy />,
- type: 'primary',
- onClick: () => {
- Modal.confirm({
- title: t('确定是否要复制此渠道?'),
- content: t('复制渠道的所有信息'),
- onOk: () => copySelectedChannel(record),
- });
- },
- },
- ];
- return (
- <Space wrap>
- <SplitButtonGroup
- className="!rounded-full overflow-hidden"
- aria-label={t('测试单个渠道操作项目组')}
- >
- <Button
- theme='light'
- size="small"
- onClick={() => testChannel(record, '')}
- >
- {t('测试')}
- </Button>
- <Button
- theme='light'
- size="small"
- icon={<IconTreeTriangleDown />}
- onClick={() => {
- setCurrentTestChannel(record);
- setShowModelTestModal(true);
- }}
- />
- </SplitButtonGroup>
- {record.status === 1 ? (
- <Button
- theme='light'
- type='warning'
- size="small"
- className="!rounded-full"
- icon={<IconStop />}
- onClick={() => manageChannel(record.id, 'disable', record)}
- >
- {t('禁用')}
- </Button>
- ) : (
- <Button
- theme='light'
- type='secondary'
- size="small"
- className="!rounded-full"
- icon={<IconPlay />}
- onClick={() => manageChannel(record.id, 'enable', record)}
- >
- {t('启用')}
- </Button>
- )}
- <Button
- theme='light'
- type='tertiary'
- size="small"
- className="!rounded-full"
- icon={<IconEdit />}
- onClick={() => {
- setEditingChannel(record);
- setShowEdit(true);
- }}
- >
- {t('编辑')}
- </Button>
- <Dropdown
- trigger='click'
- position='bottomRight'
- menu={moreMenuItems}
- >
- <Button
- icon={<IconMore />}
- theme='light'
- type='tertiary'
- size="small"
- className="!rounded-full"
- />
- </Dropdown>
- </Space>
- );
- } else {
- // 标签操作的下拉菜单项
- const tagMenuItems = [
- {
- node: 'item',
- name: t('编辑'),
- icon: <IconEdit />,
- onClick: () => {
- setShowEditTag(true);
- setEditingTag(record.key);
- },
- },
- ];
- return (
- <Space wrap>
- <Button
- theme='light'
- type='secondary'
- size="small"
- className="!rounded-full"
- icon={<IconPlay />}
- onClick={() => manageTag(record.key, 'enable')}
- >
- {t('启用全部')}
- </Button>
- <Button
- theme='light'
- type='warning'
- size="small"
- className="!rounded-full"
- icon={<IconStop />}
- onClick={() => manageTag(record.key, 'disable')}
- >
- {t('禁用全部')}
- </Button>
- <Dropdown
- trigger='click'
- position='bottomRight'
- menu={tagMenuItems}
- >
- <Button
- icon={<IconMore />}
- theme='light'
- type='tertiary'
- size="small"
- className="!rounded-full"
- />
- </Dropdown>
- </Space>
- );
- }
- },
- },
- ];
- const [channels, setChannels] = useState([]);
- const [loading, setLoading] = useState(true);
- const [activePage, setActivePage] = useState(1);
- const [idSort, setIdSort] = useState(false);
- const [searching, setSearching] = useState(false);
- const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
- const [channelCount, setChannelCount] = useState(pageSize);
- const [groupOptions, setGroupOptions] = useState([]);
- const [showEdit, setShowEdit] = useState(false);
- const [enableBatchDelete, setEnableBatchDelete] = useState(false);
- const [editingChannel, setEditingChannel] = useState({
- id: undefined,
- });
- const [showEditTag, setShowEditTag] = useState(false);
- const [editingTag, setEditingTag] = useState('');
- const [selectedChannels, setSelectedChannels] = useState([]);
- const [enableTagMode, setEnableTagMode] = useState(false);
- const [showBatchSetTag, setShowBatchSetTag] = useState(false);
- const [batchSetTagValue, setBatchSetTagValue] = useState('');
- const [showModelTestModal, setShowModelTestModal] = useState(false);
- const [currentTestChannel, setCurrentTestChannel] = useState(null);
- const [modelSearchKeyword, setModelSearchKeyword] = useState('');
- const [modelTestResults, setModelTestResults] = useState({});
- const [testingModels, setTestingModels] = useState(new Set());
- const [isBatchTesting, setIsBatchTesting] = useState(false);
- const [testQueue, setTestQueue] = useState([]);
- const [isProcessingQueue, setIsProcessingQueue] = useState(false);
- const [activeTypeKey, setActiveTypeKey] = useState('all');
- const [typeCounts, setTypeCounts] = useState({});
- const requestCounter = useRef(0);
- const [formApi, setFormApi] = useState(null);
- const [compactMode, setCompactMode] = useTableCompactMode('channels');
- const formInitValues = {
- searchKeyword: '',
- searchGroup: '',
- searchModel: '',
- };
- // Filter columns based on visibility settings
- const getVisibleColumns = () => {
- return allColumns.filter((column) => visibleColumns[column.key]);
- };
- // Column selector modal
- const renderColumnSelector = () => {
- return (
- <Modal
- title={t('列设置')}
- visible={showColumnSelector}
- onCancel={() => setShowColumnSelector(false)}
- footer={
- <div className="flex justify-end">
- <Button
- theme="light"
- onClick={() => initDefaultColumns()}
- className="!rounded-full"
- >
- {t('重置')}
- </Button>
- <Button
- theme="light"
- onClick={() => setShowColumnSelector(false)}
- className="!rounded-full"
- >
- {t('取消')}
- </Button>
- <Button
- type='primary'
- onClick={() => setShowColumnSelector(false)}
- className="!rounded-full"
- >
- {t('确定')}
- </Button>
- </div>
- }
- >
- <div style={{ marginBottom: 20 }}>
- <Checkbox
- checked={Object.values(visibleColumns).every((v) => v === true)}
- indeterminate={
- Object.values(visibleColumns).some((v) => v === true) &&
- !Object.values(visibleColumns).every((v) => v === true)
- }
- onChange={(e) => handleSelectAll(e.target.checked)}
- >
- {t('全选')}
- </Checkbox>
- </div>
- <div
- className="flex flex-wrap max-h-96 overflow-y-auto rounded-lg p-4"
- style={{ border: '1px solid var(--semi-color-border)' }}
- >
- {allColumns.map((column) => {
- // Skip columns without title
- if (!column.title) {
- return null;
- }
- return (
- <div
- key={column.key}
- className="w-1/2 mb-4 pr-2"
- >
- <Checkbox
- checked={!!visibleColumns[column.key]}
- onChange={(e) =>
- handleColumnVisibilityChange(column.key, e.target.checked)
- }
- >
- {column.title}
- </Checkbox>
- </div>
- );
- })}
- </div>
- </Modal>
- );
- };
- const removeRecord = (record) => {
- let newDataSource = [...channels];
- if (record.id != null) {
- let idx = newDataSource.findIndex((data) => {
- if (data.children !== undefined) {
- for (let i = 0; i < data.children.length; i++) {
- if (data.children[i].id === record.id) {
- data.children.splice(i, 1);
- return false;
- }
- }
- } else {
- return data.id === record.id;
- }
- });
- if (idx > -1) {
- newDataSource.splice(idx, 1);
- setChannels(newDataSource);
- }
- }
- };
- const setChannelFormat = (channels, enableTagMode) => {
- let channelDates = [];
- let channelTags = {};
- for (let i = 0; i < channels.length; i++) {
- channels[i].key = '' + channels[i].id;
- if (!enableTagMode) {
- channelDates.push(channels[i]);
- } else {
- let tag = channels[i].tag ? channels[i].tag : '';
- // find from channelTags
- let tagIndex = channelTags[tag];
- let tagChannelDates = undefined;
- if (tagIndex === undefined) {
- // not found, create a new tag
- channelTags[tag] = 1;
- tagChannelDates = {
- key: tag,
- id: tag,
- tag: tag,
- name: '标签:' + tag,
- group: '',
- used_quota: 0,
- response_time: 0,
- priority: -1,
- weight: -1,
- };
- tagChannelDates.children = [];
- channelDates.push(tagChannelDates);
- } else {
- // found, add to the tag
- tagChannelDates = channelDates.find((item) => item.key === tag);
- }
- if (tagChannelDates.priority === -1) {
- tagChannelDates.priority = channels[i].priority;
- } else {
- if (tagChannelDates.priority !== channels[i].priority) {
- tagChannelDates.priority = '';
- }
- }
- if (tagChannelDates.weight === -1) {
- tagChannelDates.weight = channels[i].weight;
- } else {
- if (tagChannelDates.weight !== channels[i].weight) {
- tagChannelDates.weight = '';
- }
- }
- if (tagChannelDates.group === '') {
- tagChannelDates.group = channels[i].group;
- } else {
- let channelGroupsStr = channels[i].group;
- channelGroupsStr.split(',').forEach((item, index) => {
- if (tagChannelDates.group.indexOf(item) === -1) {
- // join
- tagChannelDates.group += ',' + item;
- }
- });
- }
- tagChannelDates.children.push(channels[i]);
- if (channels[i].status === 1) {
- tagChannelDates.status = 1;
- }
- tagChannelDates.used_quota += channels[i].used_quota;
- tagChannelDates.response_time += channels[i].response_time;
- tagChannelDates.response_time = tagChannelDates.response_time / 2;
- }
- }
- setChannels(channelDates);
- };
- const loadChannels = async (
- page,
- pageSize,
- idSort,
- enableTagMode,
- typeKey = activeTypeKey,
- statusF,
- ) => {
- if (statusF === undefined) statusF = statusFilter;
- const { searchKeyword, searchGroup, searchModel } = getFormValues();
- if (searchKeyword !== '' || searchGroup !== '' || searchModel !== '') {
- setLoading(true);
- await searchChannels(enableTagMode, typeKey, statusF, page, pageSize, idSort);
- setLoading(false);
- return;
- }
- const reqId = ++requestCounter.current; // 记录当前请求序号
- setLoading(true);
- const typeParam = (typeKey !== 'all') ? `&type=${typeKey}` : '';
- const statusParam = statusF !== 'all' ? `&status=${statusF}` : '';
- const res = await API.get(
- `/api/channel/?p=${page}&page_size=${pageSize}&id_sort=${idSort}&tag_mode=${enableTagMode}${typeParam}${statusParam}`,
- );
- if (res === undefined || reqId !== requestCounter.current) {
- return;
- }
- const { success, message, data } = res.data;
- if (success) {
- const { items, total, type_counts } = data;
- if (type_counts) {
- const sumAll = Object.values(type_counts).reduce((acc, v) => acc + v, 0);
- setTypeCounts({ ...type_counts, all: sumAll });
- }
- setChannelFormat(items, enableTagMode);
- setChannelCount(total);
- } else {
- showError(message);
- }
- setLoading(false);
- };
- const copySelectedChannel = async (record) => {
- const channelToCopy = { ...record };
- channelToCopy.name += t('_复制');
- channelToCopy.created_time = null;
- channelToCopy.balance = 0;
- channelToCopy.used_quota = 0;
- delete channelToCopy.test_time;
- delete channelToCopy.response_time;
- if (!channelToCopy) {
- showError(t('渠道未找到,请刷新页面后重试。'));
- return;
- }
- try {
- const newChannel = { ...channelToCopy, id: undefined };
- const response = await API.post('/api/channel/', newChannel);
- if (response.data.success) {
- showSuccess(t('渠道复制成功'));
- await refresh();
- } else {
- showError(response.data.message);
- }
- } catch (error) {
- showError(t('渠道复制失败: ') + error.message);
- }
- };
- const refresh = async () => {
- const { searchKeyword, searchGroup, searchModel } = getFormValues();
- if (searchKeyword === '' && searchGroup === '' && searchModel === '') {
- await loadChannels(activePage, pageSize, idSort, enableTagMode);
- } else {
- await searchChannels(enableTagMode, activeTypeKey, statusFilter, activePage, pageSize, idSort);
- }
- };
- useEffect(() => {
- // console.log('default effect')
- const localIdSort = localStorage.getItem('id-sort') === 'true';
- const localPageSize =
- parseInt(localStorage.getItem('page-size')) || ITEMS_PER_PAGE;
- const localEnableTagMode = localStorage.getItem('enable-tag-mode') === 'true';
- const localEnableBatchDelete = localStorage.getItem('enable-batch-delete') === 'true';
- setIdSort(localIdSort);
- setPageSize(localPageSize);
- setEnableTagMode(localEnableTagMode);
- setEnableBatchDelete(localEnableBatchDelete);
- loadChannels(1, localPageSize, localIdSort, localEnableTagMode)
- .then()
- .catch((reason) => {
- showError(reason);
- });
- fetchGroups().then();
- loadChannelModels().then();
- }, []);
- const manageChannel = async (id, action, record, value) => {
- let data = { id };
- let res;
- switch (action) {
- case 'delete':
- res = await API.delete(`/api/channel/${id}/`);
- break;
- case 'enable':
- data.status = 1;
- res = await API.put('/api/channel/', data);
- break;
- case 'disable':
- data.status = 2;
- res = await API.put('/api/channel/', data);
- break;
- case 'priority':
- if (value === '') {
- return;
- }
- data.priority = parseInt(value);
- res = await API.put('/api/channel/', data);
- break;
- case 'weight':
- if (value === '') {
- return;
- }
- data.weight = parseInt(value);
- if (data.weight < 0) {
- data.weight = 0;
- }
- res = await API.put('/api/channel/', data);
- break;
- }
- const { success, message } = res.data;
- if (success) {
- showSuccess(t('操作成功完成!'));
- let channel = res.data.data;
- let newChannels = [...channels];
- if (action === 'delete') {
- } else {
- record.status = channel.status;
- }
- setChannels(newChannels);
- } else {
- showError(message);
- }
- };
- const manageTag = async (tag, action) => {
- console.log(tag, action);
- let res;
- switch (action) {
- case 'enable':
- res = await API.post('/api/channel/tag/enabled', {
- tag: tag,
- });
- break;
- case 'disable':
- res = await API.post('/api/channel/tag/disabled', {
- tag: tag,
- });
- break;
- }
- const { success, message } = res.data;
- if (success) {
- showSuccess('操作成功完成!');
- let newChannels = [...channels];
- for (let i = 0; i < newChannels.length; i++) {
- if (newChannels[i].tag === tag) {
- let status = action === 'enable' ? 1 : 2;
- newChannels[i]?.children?.forEach((channel) => {
- channel.status = status;
- });
- newChannels[i].status = status;
- }
- }
- setChannels(newChannels);
- } else {
- showError(message);
- }
- };
- // 获取表单值的辅助函数
- const getFormValues = () => {
- const formValues = formApi ? formApi.getValues() : {};
- return {
- searchKeyword: formValues.searchKeyword || '',
- searchGroup: formValues.searchGroup || '',
- searchModel: formValues.searchModel || '',
- };
- };
- const searchChannels = async (
- enableTagMode,
- typeKey = activeTypeKey,
- statusF = statusFilter,
- page = 1,
- pageSz = pageSize,
- sortFlag = idSort,
- ) => {
- const { searchKeyword, searchGroup, searchModel } = getFormValues();
- setSearching(true);
- try {
- if (searchKeyword === '' && searchGroup === '' && searchModel === '') {
- await loadChannels(page, pageSz, sortFlag, enableTagMode, typeKey, statusF);
- return;
- }
- const typeParam = (typeKey !== 'all') ? `&type=${typeKey}` : '';
- const statusParam = statusF !== 'all' ? `&status=${statusF}` : '';
- const res = await API.get(
- `/api/channel/search?keyword=${searchKeyword}&group=${searchGroup}&model=${searchModel}&id_sort=${sortFlag}&tag_mode=${enableTagMode}&p=${page}&page_size=${pageSz}${typeParam}${statusParam}`,
- );
- const { success, message, data } = res.data;
- if (success) {
- const { items = [], total = 0, type_counts = {} } = data;
- const sumAll = Object.values(type_counts).reduce((acc, v) => acc + v, 0);
- setTypeCounts({ ...type_counts, all: sumAll });
- setChannelFormat(items, enableTagMode);
- setChannelCount(total);
- setActivePage(page);
- } else {
- showError(message);
- }
- } finally {
- setSearching(false);
- }
- };
- const updateChannelProperty = (channelId, updateFn) => {
- // Create a new copy of channels array
- const newChannels = [...channels];
- let updated = false;
- // Find and update the correct channel
- newChannels.forEach((channel) => {
- if (channel.children !== undefined) {
- // If this is a tag group, search in its children
- channel.children.forEach((child) => {
- if (child.id === channelId) {
- updateFn(child);
- updated = true;
- }
- });
- } else if (channel.id === channelId) {
- // Direct channel match
- updateFn(channel);
- updated = true;
- }
- });
- // Only update state if we actually modified a channel
- if (updated) {
- setChannels(newChannels);
- }
- };
- const processTestQueue = async () => {
- if (!isProcessingQueue || testQueue.length === 0) return;
- const { channel, model } = testQueue[0];
- try {
- setTestingModels(prev => new Set([...prev, model]));
- const res = await API.get(`/api/channel/test/${channel.id}?model=${model}`);
- const { success, message, time } = res.data;
- setModelTestResults(prev => ({
- ...prev,
- [`${channel.id}-${model}`]: { success, time }
- }));
- if (success) {
- updateChannelProperty(channel.id, (ch) => {
- ch.response_time = time * 1000;
- ch.test_time = Date.now() / 1000;
- });
- if (!model) {
- showInfo(
- t('通道 ${name} 测试成功,耗时 ${time.toFixed(2)} 秒。')
- .replace('${name}', channel.name)
- .replace('${time.toFixed(2)}', time.toFixed(2)),
- );
- }
- } else {
- showError(message);
- }
- } catch (error) {
- showError(error.message);
- } finally {
- setTestingModels(prev => {
- const newSet = new Set(prev);
- newSet.delete(model);
- return newSet;
- });
- }
- // 移除已处理的测试
- setTestQueue(prev => prev.slice(1));
- };
- // 监听队列变化
- useEffect(() => {
- if (testQueue.length > 0 && isProcessingQueue) {
- processTestQueue();
- } else if (testQueue.length === 0 && isProcessingQueue) {
- setIsProcessingQueue(false);
- setIsBatchTesting(false);
- }
- }, [testQueue, isProcessingQueue]);
- const testChannel = async (record, model) => {
- setTestQueue(prev => [...prev, { channel: record, model }]);
- if (!isProcessingQueue) {
- setIsProcessingQueue(true);
- }
- };
- const batchTestModels = async () => {
- if (!currentTestChannel) return;
- setIsBatchTesting(true);
- const models = currentTestChannel.models
- .split(',')
- .filter((model) =>
- model.toLowerCase().includes(modelSearchKeyword.toLowerCase())
- );
- setTestQueue(models.map(model => ({
- channel: currentTestChannel,
- model
- })));
- setIsProcessingQueue(true);
- };
- const handleCloseModal = () => {
- if (isBatchTesting) {
- // 清空测试队列来停止测试
- setTestQueue([]);
- setIsProcessingQueue(false);
- setIsBatchTesting(false);
- showSuccess(t('已停止测试'));
- } else {
- setShowModelTestModal(false);
- setModelSearchKeyword('');
- }
- };
- const channelTypeCounts = useMemo(() => {
- if (Object.keys(typeCounts).length > 0) return typeCounts;
- // fallback 本地计算
- const counts = { all: channels.length };
- channels.forEach((channel) => {
- const collect = (ch) => {
- const type = ch.type;
- counts[type] = (counts[type] || 0) + 1;
- };
- if (channel.children !== undefined) {
- channel.children.forEach(collect);
- } else {
- collect(channel);
- }
- });
- return counts;
- }, [typeCounts, channels]);
- const availableTypeKeys = useMemo(() => {
- const keys = ['all'];
- Object.entries(channelTypeCounts).forEach(([k, v]) => {
- if (k !== 'all' && v > 0) keys.push(String(k));
- });
- return keys;
- }, [channelTypeCounts]);
- const renderTypeTabs = () => {
- if (enableTagMode) return null;
- return (
- <Tabs
- activeKey={activeTypeKey}
- type="card"
- collapsible
- onChange={(key) => {
- setActiveTypeKey(key);
- setActivePage(1);
- loadChannels(1, pageSize, idSort, enableTagMode, key);
- }}
- className="mb-4"
- >
- <TabPane
- itemKey="all"
- tab={
- <span className="flex items-center gap-2">
- {t('全部')}
- <Tag color={activeTypeKey === 'all' ? 'red' : 'grey'} size='small' shape='circle'>
- {channelTypeCounts['all'] || 0}
- </Tag>
- </span>
- }
- />
- {CHANNEL_OPTIONS.filter((opt) => availableTypeKeys.includes(String(opt.value))).map((option) => {
- const key = String(option.value);
- const count = channelTypeCounts[option.value] || 0;
- return (
- <TabPane
- key={key}
- itemKey={key}
- tab={
- <span className="flex items-center gap-2">
- {getChannelIcon(option.value)}
- {option.label}
- <Tag color={activeTypeKey === key ? 'red' : 'grey'} size='small' shape='circle'>
- {count}
- </Tag>
- </span>
- }
- />
- );
- })}
- </Tabs>
- );
- };
- let pageData = channels;
- const handlePageChange = (page) => {
- const { searchKeyword, searchGroup, searchModel } = getFormValues();
- setActivePage(page);
- if (searchKeyword === '' && searchGroup === '' && searchModel === '') {
- loadChannels(page, pageSize, idSort, enableTagMode).then(() => { });
- } else {
- searchChannels(enableTagMode, activeTypeKey, statusFilter, page, pageSize, idSort);
- }
- };
- const handlePageSizeChange = async (size) => {
- localStorage.setItem('page-size', size + '');
- setPageSize(size);
- setActivePage(1);
- const { searchKeyword, searchGroup, searchModel } = getFormValues();
- if (searchKeyword === '' && searchGroup === '' && searchModel === '') {
- loadChannels(1, size, idSort, enableTagMode)
- .then()
- .catch((reason) => {
- showError(reason);
- });
- } else {
- searchChannels(enableTagMode, activeTypeKey, statusFilter, 1, size, idSort);
- }
- };
- const fetchGroups = async () => {
- try {
- let res = await API.get(`/api/group/`);
- if (res === undefined) {
- return;
- }
- setGroupOptions(
- res.data.data.map((group) => ({
- label: group,
- value: group,
- })),
- );
- } catch (error) {
- showError(error.message);
- }
- };
- const submitTagEdit = async (type, data) => {
- switch (type) {
- case 'priority':
- if (data.priority === undefined || data.priority === '') {
- showInfo('优先级必须是整数!');
- return;
- }
- data.priority = parseInt(data.priority);
- break;
- case 'weight':
- if (
- data.weight === undefined ||
- data.weight < 0 ||
- data.weight === ''
- ) {
- showInfo('权重必须是非负整数!');
- return;
- }
- data.weight = parseInt(data.weight);
- break;
- }
- try {
- const res = await API.put('/api/channel/tag', data);
- if (res?.data?.success) {
- showSuccess('更新成功!');
- await refresh();
- }
- } catch (error) {
- showError(error);
- }
- };
- const closeEdit = () => {
- setShowEdit(false);
- };
- const handleRow = (record, index) => {
- if (record.status !== 1) {
- return {
- style: {
- background: 'var(--semi-color-disabled-border)',
- },
- };
- } else {
- return {};
- }
- };
- const batchSetChannelTag = async () => {
- if (selectedChannels.length === 0) {
- showError(t('请先选择要设置标签的渠道!'));
- return;
- }
- if (batchSetTagValue === '') {
- showError(t('标签不能为空!'));
- return;
- }
- let ids = selectedChannels.map((channel) => channel.id);
- const res = await API.post('/api/channel/batch/tag', {
- ids: ids,
- tag: batchSetTagValue === '' ? null : batchSetTagValue,
- });
- if (res.data.success) {
- showSuccess(
- t('已为 ${count} 个渠道设置标签!').replace('${count}', res.data.data),
- );
- await refresh();
- setShowBatchSetTag(false);
- } else {
- showError(res.data.message);
- }
- };
- const testAllChannels = async () => {
- const res = await API.get(`/api/channel/test`);
- const { success, message } = res.data;
- if (success) {
- showInfo(t('已成功开始测试所有已启用通道,请刷新页面查看结果。'));
- } else {
- showError(message);
- }
- };
- const deleteAllDisabledChannels = async () => {
- const res = await API.delete(`/api/channel/disabled`);
- const { success, message, data } = res.data;
- if (success) {
- showSuccess(
- t('已删除所有禁用渠道,共计 ${data} 个').replace('${data}', data),
- );
- await refresh();
- } else {
- showError(message);
- }
- };
- const updateAllChannelsBalance = async () => {
- const res = await API.get(`/api/channel/update_balance`);
- const { success, message } = res.data;
- if (success) {
- showInfo(t('已更新完毕所有已启用通道余额!'));
- } else {
- showError(message);
- }
- };
- const updateChannelBalance = async (record) => {
- const res = await API.get(`/api/channel/update_balance/${record.id}/`);
- const { success, message, balance } = res.data;
- if (success) {
- updateChannelProperty(record.id, (channel) => {
- channel.balance = balance;
- channel.balance_updated_time = Date.now() / 1000;
- });
- showInfo(
- t('通道 ${name} 余额更新成功!').replace('${name}', record.name),
- );
- } else {
- showError(message);
- }
- };
- const batchDeleteChannels = async () => {
- if (selectedChannels.length === 0) {
- showError(t('请先选择要删除的通道!'));
- return;
- }
- setLoading(true);
- let ids = [];
- selectedChannels.forEach((channel) => {
- ids.push(channel.id);
- });
- const res = await API.post(`/api/channel/batch`, { ids: ids });
- const { success, message, data } = res.data;
- if (success) {
- showSuccess(t('已删除 ${data} 个通道!').replace('${data}', data));
- await refresh();
- } else {
- showError(message);
- }
- setLoading(false);
- };
- const fixChannelsAbilities = async () => {
- const res = await API.post(`/api/channel/fix`);
- const { success, message, data } = res.data;
- if (success) {
- showSuccess(t('已修复 ${data} 个通道!').replace('${data}', data));
- await refresh();
- } else {
- showError(message);
- }
- };
- const renderHeader = () => (
- <div className="flex flex-col w-full">
- {renderTypeTabs()}
- <div className="flex flex-col md:flex-row justify-between gap-4">
- <div className="flex flex-wrap md:flex-nowrap items-center gap-2 w-full md:w-auto order-2 md:order-1">
- <Button
- disabled={!enableBatchDelete}
- theme='light'
- type='danger'
- className="!rounded-full w-full md:w-auto"
- onClick={() => {
- Modal.confirm({
- title: t('确定是否要删除所选通道?'),
- content: t('此修改将不可逆'),
- onOk: () => batchDeleteChannels(),
- });
- }}
- >
- {t('删除所选通道')}
- </Button>
- <Button
- disabled={!enableBatchDelete}
- theme='light'
- type='primary'
- onClick={() => setShowBatchSetTag(true)}
- className="!rounded-full w-full md:w-auto"
- >
- {t('批量设置标签')}
- </Button>
- <Dropdown
- trigger='click'
- render={
- <Dropdown.Menu>
- <Dropdown.Item>
- <Button
- theme='light'
- type='warning'
- className="!rounded-full w-full"
- onClick={() => {
- Modal.confirm({
- title: t('确定?'),
- content: t('确定要测试所有通道吗?'),
- onOk: () => testAllChannels(),
- size: 'small',
- centered: true,
- });
- }}
- >
- {t('测试所有通道')}
- </Button>
- </Dropdown.Item>
- <Dropdown.Item>
- <Button
- theme='light'
- type='secondary'
- className="!rounded-full w-full"
- onClick={() => {
- Modal.confirm({
- title: t('确定?'),
- content: t('确定要更新所有已启用通道余额吗?'),
- onOk: () => updateAllChannelsBalance(),
- size: 'sm',
- centered: true,
- });
- }}
- >
- {t('更新所有已启用通道余额')}
- </Button>
- </Dropdown.Item>
- <Dropdown.Item>
- <Button
- theme='light'
- type='danger'
- className="!rounded-full w-full"
- onClick={() => {
- Modal.confirm({
- title: t('确定是否要删除禁用通道?'),
- content: t('此修改将不可逆'),
- onOk: () => deleteAllDisabledChannels(),
- size: 'sm',
- centered: true,
- });
- }}
- >
- {t('删除禁用通道')}
- </Button>
- </Dropdown.Item>
- <Dropdown.Item>
- <Button
- theme='light'
- type='tertiary'
- className="!rounded-full w-full"
- onClick={() => {
- Modal.confirm({
- title: t('确定是否要修复数据库一致性?'),
- content: t('进行该操作时,可能导致渠道访问错误,请仅在数据库出现问题时使用'),
- onOk: () => fixChannelsAbilities(),
- size: 'sm',
- centered: true,
- });
- }}
- >
- {t('修复数据库一致性')}
- </Button>
- </Dropdown.Item>
- </Dropdown.Menu>
- }
- >
- <Button theme='light' type='tertiary' icon={<IconSetting />} className="!rounded-full w-full md:w-auto">
- {t('批量操作')}
- </Button>
- </Dropdown>
- <Button
- theme='light'
- type='secondary'
- icon={<IconDescend />}
- className="!rounded-full w-full md:w-auto"
- onClick={() => setCompactMode(!compactMode)}
- >
- {compactMode ? t('自适应列表') : t('紧凑列表')}
- </Button>
- </div>
- <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">
- <div className="flex items-center justify-between w-full md:w-auto">
- <Typography.Text strong className="mr-2">
- {t('使用ID排序')}
- </Typography.Text>
- <Switch
- checked={idSort}
- onChange={(v) => {
- localStorage.setItem('id-sort', v + '');
- setIdSort(v);
- const { searchKeyword, searchGroup, searchModel } = getFormValues();
- if (searchKeyword === '' && searchGroup === '' && searchModel === '') {
- loadChannels(activePage, pageSize, v, enableTagMode);
- } else {
- searchChannels(enableTagMode, activeTypeKey, statusFilter, activePage, pageSize, v);
- }
- }}
- />
- </div>
- <div className="flex items-center justify-between w-full md:w-auto">
- <Typography.Text strong className="mr-2">
- {t('开启批量操作')}
- </Typography.Text>
- <Switch
- checked={enableBatchDelete}
- onChange={(v) => {
- localStorage.setItem('enable-batch-delete', v + '');
- setEnableBatchDelete(v);
- }}
- />
- </div>
- <div className="flex items-center justify-between w-full md:w-auto">
- <Typography.Text strong className="mr-2">
- {t('标签聚合模式')}
- </Typography.Text>
- <Switch
- checked={enableTagMode}
- onChange={(v) => {
- localStorage.setItem('enable-tag-mode', v + '');
- setEnableTagMode(v);
- setActivePage(1);
- loadChannels(1, pageSize, idSort, v);
- }}
- />
- </div>
- {/* 状态筛选器 */}
- <div className="flex items-center justify-between w-full md:w-auto">
- <Typography.Text strong className="mr-2">
- {t('状态筛选')}
- </Typography.Text>
- <Select
- value={statusFilter}
- onChange={(v) => {
- localStorage.setItem('channel-status-filter', v);
- setStatusFilter(v);
- setActivePage(1);
- loadChannels(1, pageSize, idSort, enableTagMode, activeTypeKey, v);
- }}
- size="small"
- >
- <Select.Option value="all">{t('全部')}</Select.Option>
- <Select.Option value="enabled">{t('已启用')}</Select.Option>
- <Select.Option value="disabled">{t('已禁用')}</Select.Option>
- </Select>
- </div>
- </div>
- </div>
- <Divider margin="12px" />
- <div className="flex flex-col md:flex-row justify-between items-center gap-4 w-full">
- <div className="flex gap-2 w-full md:w-auto order-2 md:order-1">
- <Button
- theme='light'
- type='primary'
- icon={<IconPlus />}
- className="!rounded-full w-full md:w-auto"
- onClick={() => {
- setEditingChannel({
- id: undefined,
- });
- setShowEdit(true);
- }}
- >
- {t('添加渠道')}
- </Button>
- <Button
- theme='light'
- type='primary'
- icon={<IconRefresh />}
- className="!rounded-full w-full md:w-auto"
- onClick={refresh}
- >
- {t('刷新')}
- </Button>
- <Button
- theme='light'
- type='tertiary'
- icon={<IconSetting />}
- onClick={() => setShowColumnSelector(true)}
- className="!rounded-full w-full md:w-auto"
- >
- {t('列设置')}
- </Button>
- </div>
- <div className="flex flex-col md:flex-row items-center gap-4 w-full md:w-auto order-1 md:order-2">
- <Form
- initValues={formInitValues}
- getFormApi={(api) => setFormApi(api)}
- onSubmit={() => searchChannels(enableTagMode)}
- allowEmpty={true}
- autoComplete="off"
- layout="horizontal"
- trigger="change"
- stopValidateWithError={false}
- className="flex flex-col md:flex-row items-center gap-4 w-full"
- >
- <div className="relative w-full md:w-64">
- <Form.Input
- field="searchKeyword"
- prefix={<IconSearch />}
- placeholder={t('渠道ID,名称,密钥,API地址')}
- className="!rounded-full"
- showClear
- pure
- />
- </div>
- <div className="w-full md:w-48">
- <Form.Input
- field="searchModel"
- prefix={<IconSearch />}
- placeholder={t('模型关键字')}
- className="!rounded-full"
- showClear
- pure
- />
- </div>
- <div className="w-full md:w-48">
- <Form.Select
- field="searchGroup"
- placeholder={t('选择分组')}
- optionList={[
- { label: t('选择分组'), value: null },
- ...groupOptions,
- ]}
- className="!rounded-full w-full"
- showClear
- pure
- onChange={() => {
- // 延迟执行搜索,让表单值先更新
- setTimeout(() => {
- searchChannels(enableTagMode);
- }, 0);
- }}
- />
- </div>
- <Button
- type="primary"
- htmlType="submit"
- loading={loading || searching}
- className="!rounded-full w-full md:w-auto"
- >
- {t('查询')}
- </Button>
- <Button
- theme='light'
- onClick={() => {
- if (formApi) {
- formApi.reset();
- // 重置后立即查询,使用setTimeout确保表单重置完成
- setTimeout(() => {
- refresh();
- }, 100);
- }
- }}
- className="!rounded-full w-full md:w-auto"
- >
- {t('重置')}
- </Button>
- </Form>
- </div>
- </div>
- </div>
- );
- return (
- <>
- {renderColumnSelector()}
- <EditTagModal
- visible={showEditTag}
- tag={editingTag}
- handleClose={() => setShowEditTag(false)}
- refresh={refresh}
- />
- <EditChannel
- refresh={refresh}
- visible={showEdit}
- handleClose={closeEdit}
- editingChannel={editingChannel}
- />
- <Card
- className="!rounded-2xl"
- title={renderHeader()}
- shadows='always'
- bordered={false}
- >
- <Table
- columns={compactMode ? getVisibleColumns().map(({ fixed, ...rest }) => rest) : getVisibleColumns()}
- dataSource={pageData}
- scroll={compactMode ? undefined : { x: 'max-content' }}
- pagination={{
- currentPage: activePage,
- pageSize: pageSize,
- total: channelCount,
- pageSizeOpts: [10, 20, 50, 100],
- showSizeChanger: true,
- formatPageText: (page) => t('第 {{start}} - {{end}} 条,共 {{total}} 条', {
- start: page.currentStart,
- end: page.currentEnd,
- total: channelCount,
- }),
- onPageSizeChange: (size) => {
- handlePageSizeChange(size);
- },
- onPageChange: handlePageChange,
- }}
- expandAllRows={false}
- onRow={handleRow}
- rowSelection={
- enableBatchDelete
- ? {
- onChange: (selectedRowKeys, selectedRows) => {
- setSelectedChannels(selectedRows);
- },
- }
- : null
- }
- empty={
- <Empty
- image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
- darkModeImage={<IllustrationNoResultDark style={{ width: 150, height: 150 }} />}
- description={t('搜索无结果')}
- style={{ padding: 30 }}
- />
- }
- className="rounded-xl overflow-hidden"
- size="middle"
- loading={loading}
- />
- </Card>
- {/* 批量设置标签模态框 */}
- <Modal
- title={t('批量设置标签')}
- visible={showBatchSetTag}
- onOk={batchSetChannelTag}
- onCancel={() => setShowBatchSetTag(false)}
- maskClosable={false}
- centered={true}
- size="small"
- className="!rounded-lg"
- >
- <div className="mb-5">
- <Typography.Text>{t('请输入要设置的标签名称')}</Typography.Text>
- </div>
- <Input
- placeholder={t('请输入标签名称')}
- value={batchSetTagValue}
- onChange={(v) => setBatchSetTagValue(v)}
- size='large'
- className="!rounded-full"
- />
- <div className="mt-4">
- <Typography.Text type='secondary'>
- {t('已选择 ${count} 个渠道').replace('${count}', selectedChannels.length)}
- </Typography.Text>
- </div>
- </Modal>
- {/* 模型测试弹窗 */}
- <Modal
- title={
- currentTestChannel && (
- <div className="flex items-center gap-2">
- <Typography.Text strong className="!text-[var(--semi-color-text-0)] !text-base">
- {currentTestChannel.name} {t('渠道的模型测试')}
- </Typography.Text>
- <Typography.Text type="tertiary" className="!text-xs flex items-center">
- {t('共')} {currentTestChannel.models.split(',').length} {t('个模型')}
- </Typography.Text>
- </div>
- )
- }
- visible={showModelTestModal && currentTestChannel !== null}
- onCancel={handleCloseModal}
- footer={
- <div className="flex justify-end">
- {isBatchTesting ? (
- <Button
- theme='light'
- type='warning'
- className="!rounded-full"
- onClick={handleCloseModal}
- >
- {t('停止测试')}
- </Button>
- ) : (
- <Button
- theme='light'
- type='tertiary'
- className="!rounded-full"
- onClick={handleCloseModal}
- >
- {t('取消')}
- </Button>
- )}
- <Button
- theme='light'
- type='primary'
- className="!rounded-full"
- onClick={batchTestModels}
- loading={isBatchTesting}
- disabled={isBatchTesting}
- >
- {isBatchTesting ? t('测试中...') : t('批量测试${count}个模型').replace(
- '${count}',
- currentTestChannel
- ? currentTestChannel.models
- .split(',')
- .filter((model) =>
- model.toLowerCase().includes(modelSearchKeyword.toLowerCase())
- ).length
- : 0
- )}
- </Button>
- </div>
- }
- maskClosable={!isBatchTesting}
- className="!rounded-lg"
- size="large"
- >
- <div className="max-h-[600px] overflow-y-auto">
- {currentTestChannel && (
- <div>
- <div className="flex items-center justify-end mb-2">
- <Input
- placeholder={t('搜索模型...')}
- value={modelSearchKeyword}
- onChange={(v) => setModelSearchKeyword(v)}
- className="w-64 !rounded-full"
- prefix={<IconSearch />}
- showClear
- />
- </div>
- <Table
- columns={[
- {
- title: t('模型名称'),
- dataIndex: 'model',
- render: (text) => (
- <div className="flex items-center">
- <Typography.Text strong>{text}</Typography.Text>
- </div>
- )
- },
- {
- title: t('状态'),
- dataIndex: 'status',
- render: (text, record) => {
- const testResult = modelTestResults[`${currentTestChannel.id}-${record.model}`];
- const isTesting = testingModels.has(record.model);
- if (isTesting) {
- return (
- <Tag size='large' color='blue' className="!rounded-full">
- {t('测试中')}
- </Tag>
- );
- }
- if (!testResult) {
- return (
- <Tag size='large' color='grey' className="!rounded-full">
- {t('未开始')}
- </Tag>
- );
- }
- return (
- <div className="flex items-center gap-2">
- <Tag
- size='large'
- color={testResult.success ? 'green' : 'red'}
- className="!rounded-full"
- >
- {testResult.success ? t('成功') : t('失败')}
- </Tag>
- {testResult.success && (
- <Typography.Text type="tertiary">
- {t('请求时长: ${time}s').replace('${time}', testResult.time.toFixed(2))}
- </Typography.Text>
- )}
- </div>
- );
- }
- },
- {
- title: '',
- dataIndex: 'operate',
- render: (text, record) => {
- const isTesting = testingModels.has(record.model);
- return (
- <Button
- theme='light'
- type='primary'
- className="!rounded-full"
- onClick={() => testChannel(currentTestChannel, record.model)}
- loading={isTesting}
- size='small'
- icon={<IconSmallTriangleRight />}
- >
- {t('测试')}
- </Button>
- );
- }
- }
- ]}
- dataSource={currentTestChannel.models
- .split(',')
- .filter((model) =>
- model.toLowerCase().includes(modelSearchKeyword.toLowerCase())
- )
- .map((model) => ({
- model,
- key: model
- }))}
- pagination={false}
- />
- </div>
- )}
- </div>
- </Modal>
- </>
- );
- };
- export default ChannelsTable;
|