UpstreamRatioSync.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. import React, { useState, useCallback, useMemo } from 'react';
  2. import {
  3. Button,
  4. Table,
  5. Tag,
  6. Empty,
  7. Checkbox,
  8. Form,
  9. } from '@douyinfe/semi-ui';
  10. import {
  11. RefreshCcw,
  12. CheckSquare,
  13. } from 'lucide-react';
  14. import { API, showError, showSuccess, showWarning } from '../../../helpers';
  15. import { DEFAULT_ENDPOINT } from '../../../constants';
  16. import { useTranslation } from 'react-i18next';
  17. import {
  18. IllustrationNoResult,
  19. IllustrationNoResultDark
  20. } from '@douyinfe/semi-illustrations';
  21. import ChannelSelectorModal from '../../../components/settings/ChannelSelectorModal';
  22. export default function UpstreamRatioSync(props) {
  23. const { t } = useTranslation();
  24. const [modalVisible, setModalVisible] = useState(false);
  25. const [loading, setLoading] = useState(false);
  26. const [syncLoading, setSyncLoading] = useState(false);
  27. // 渠道选择相关
  28. const [allChannels, setAllChannels] = useState([]);
  29. const [selectedChannelIds, setSelectedChannelIds] = useState([]);
  30. // 渠道端点配置
  31. const [channelEndpoints, setChannelEndpoints] = useState({}); // { channelId: endpoint }
  32. // 差异数据和测试结果
  33. const [differences, setDifferences] = useState({});
  34. const [testResults, setTestResults] = useState([]);
  35. const [resolutions, setResolutions] = useState({});
  36. // 分页相关状态
  37. const [currentPage, setCurrentPage] = useState(1);
  38. const [pageSize, setPageSize] = useState(10);
  39. // 获取所有渠道
  40. const fetchAllChannels = async () => {
  41. setLoading(true);
  42. try {
  43. const res = await API.get('/api/ratio_sync/channels');
  44. if (res.data.success) {
  45. const channels = res.data.data || [];
  46. // 转换为Transfer组件所需格式
  47. const transferData = channels.map(channel => ({
  48. key: channel.id,
  49. label: channel.name,
  50. value: channel.id,
  51. disabled: false, // 所有渠道都可以选择
  52. _originalData: channel,
  53. }));
  54. setAllChannels(transferData);
  55. // 初始化端点配置
  56. const initialEndpoints = {};
  57. transferData.forEach(channel => {
  58. initialEndpoints[channel.key] = DEFAULT_ENDPOINT;
  59. });
  60. setChannelEndpoints(initialEndpoints);
  61. } else {
  62. showError(res.data.message);
  63. }
  64. } catch (error) {
  65. showError(t('获取渠道失败:') + error.message);
  66. } finally {
  67. setLoading(false);
  68. }
  69. };
  70. // 确认选择渠道
  71. const confirmChannelSelection = () => {
  72. const selected = allChannels
  73. .filter(ch => selectedChannelIds.includes(ch.value))
  74. .map(ch => ch._originalData);
  75. if (selected.length === 0) {
  76. showWarning(t('请至少选择一个渠道'));
  77. return;
  78. }
  79. setModalVisible(false);
  80. fetchRatiosFromChannels(selected);
  81. };
  82. // 从选定渠道获取倍率
  83. const fetchRatiosFromChannels = async (channelList) => {
  84. setSyncLoading(true);
  85. const payload = {
  86. channel_ids: channelList.map(ch => parseInt(ch.id)),
  87. timeout: 10,
  88. };
  89. try {
  90. const res = await API.post('/api/ratio_sync/fetch', payload);
  91. if (!res.data.success) {
  92. showError(res.data.message || t('后端请求失败'));
  93. setSyncLoading(false);
  94. return;
  95. }
  96. const { differences = {}, test_results = [] } = res.data.data;
  97. // 显示测试结果
  98. const errorResults = test_results.filter(r => r.status === 'error');
  99. if (errorResults.length > 0) {
  100. showWarning(t('部分渠道测试失败:') + errorResults.map(r => `${r.name}: ${r.error}`).join(', '));
  101. }
  102. setDifferences(differences);
  103. setTestResults(test_results);
  104. setResolutions({});
  105. // 判断是否有差异
  106. if (Object.keys(differences).length === 0) {
  107. showSuccess(t('已与上游倍率完全一致,无需同步'));
  108. }
  109. } catch (e) {
  110. showError(t('请求后端接口失败:') + e.message);
  111. } finally {
  112. setSyncLoading(false);
  113. }
  114. };
  115. // 解决冲突/选择值
  116. const selectValue = (model, ratioType, value) => {
  117. setResolutions(prev => ({
  118. ...prev,
  119. [model]: {
  120. ...prev[model],
  121. [ratioType]: value,
  122. },
  123. }));
  124. };
  125. // 应用同步
  126. const applySync = async () => {
  127. const currentRatios = {
  128. ModelRatio: JSON.parse(props.options.ModelRatio || '{}'),
  129. CompletionRatio: JSON.parse(props.options.CompletionRatio || '{}'),
  130. CacheRatio: JSON.parse(props.options.CacheRatio || '{}'),
  131. ModelPrice: JSON.parse(props.options.ModelPrice || '{}'),
  132. };
  133. // 应用已选择的值
  134. Object.entries(resolutions).forEach(([model, ratios]) => {
  135. Object.entries(ratios).forEach(([ratioType, value]) => {
  136. const optionKey = ratioType
  137. .split('_')
  138. .map(word => word.charAt(0).toUpperCase() + word.slice(1))
  139. .join('');
  140. currentRatios[optionKey][model] = parseFloat(value);
  141. });
  142. });
  143. // 保存到后端
  144. setLoading(true);
  145. try {
  146. const updates = Object.entries(currentRatios).map(([key, value]) =>
  147. API.put('/api/option/', {
  148. key,
  149. value: JSON.stringify(value, null, 2),
  150. })
  151. );
  152. const results = await Promise.all(updates);
  153. if (results.every(res => res.data.success)) {
  154. showSuccess(t('同步成功'));
  155. props.refresh();
  156. // 清空状态
  157. setDifferences({});
  158. setTestResults([]);
  159. setResolutions({});
  160. setSelectedChannelIds([]);
  161. } else {
  162. showError(t('部分保存失败'));
  163. }
  164. } catch (error) {
  165. showError(t('保存失败'));
  166. } finally {
  167. setLoading(false);
  168. }
  169. };
  170. // 计算当前页显示的数据
  171. const getCurrentPageData = (dataSource) => {
  172. const startIndex = (currentPage - 1) * pageSize;
  173. const endIndex = startIndex + pageSize;
  174. return dataSource.slice(startIndex, endIndex);
  175. };
  176. // 渲染表格头部
  177. const renderHeader = () => (
  178. <div className="flex flex-col w-full">
  179. <div className="flex flex-col md:flex-row justify-between items-center gap-4 w-full">
  180. <div className="flex gap-2 w-full md:w-auto order-2 md:order-1">
  181. <Button
  182. icon={<RefreshCcw size={14} />}
  183. className="!rounded-full w-full md:w-auto mt-2"
  184. onClick={() => {
  185. setModalVisible(true);
  186. fetchAllChannels();
  187. }}
  188. >
  189. {t('选择同步渠道')}
  190. </Button>
  191. {(() => {
  192. // 检查是否有选择可应用的值
  193. const hasSelections = Object.keys(resolutions).length > 0;
  194. return (
  195. <Button
  196. icon={<CheckSquare size={14} />}
  197. type='secondary'
  198. onClick={applySync}
  199. disabled={!hasSelections}
  200. className="!rounded-full w-full md:w-auto mt-2"
  201. >
  202. {t('应用同步')}
  203. </Button>
  204. );
  205. })()}
  206. </div>
  207. </div>
  208. </div>
  209. );
  210. // 渲染差异表格
  211. const renderDifferenceTable = () => {
  212. // 构建数据源
  213. const dataSource = useMemo(() => {
  214. const tmp = [];
  215. Object.entries(differences).forEach(([model, ratioTypes]) => {
  216. Object.entries(ratioTypes).forEach(([ratioType, diff]) => {
  217. tmp.push({
  218. key: `${model}_${ratioType}`,
  219. model,
  220. ratioType,
  221. current: diff.current,
  222. upstreams: diff.upstreams,
  223. });
  224. });
  225. });
  226. return tmp;
  227. }, [differences]);
  228. // 收集所有上游渠道名称
  229. const upstreamNames = useMemo(() => {
  230. const set = new Set();
  231. dataSource.forEach((row) => {
  232. Object.keys(row.upstreams || {}).forEach((name) => set.add(name));
  233. });
  234. return Array.from(set);
  235. }, [dataSource]);
  236. if (dataSource.length === 0) {
  237. return (
  238. <Empty
  239. image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
  240. darkModeImage={<IllustrationNoResultDark style={{ width: 150, height: 150 }} />}
  241. description={Object.keys(differences).length === 0 ? t('已与上游倍率完全一致') : t('请先选择同步渠道')}
  242. style={{ padding: 30 }}
  243. />
  244. );
  245. }
  246. // 列定义
  247. const columns = [
  248. {
  249. title: t('模型'),
  250. dataIndex: 'model',
  251. fixed: 'left',
  252. },
  253. {
  254. title: t('倍率类型'),
  255. dataIndex: 'ratioType',
  256. render: (text) => {
  257. const typeMap = {
  258. model_ratio: t('模型倍率'),
  259. completion_ratio: t('补全倍率'),
  260. cache_ratio: t('缓存倍率'),
  261. model_price: t('固定价格'),
  262. };
  263. return <Tag shape="circle">{typeMap[text] || text}</Tag>;
  264. },
  265. },
  266. {
  267. title: t('当前值'),
  268. dataIndex: 'current',
  269. render: (text) => (
  270. <Tag color={text !== null && text !== undefined ? 'blue' : 'default'} shape="circle">
  271. {text !== null && text !== undefined ? text : t('未设置')}
  272. </Tag>
  273. ),
  274. },
  275. // 动态上游列
  276. ...upstreamNames.map((upName) => {
  277. // 计算该渠道的全选状态
  278. const channelStats = (() => {
  279. let selectableCount = 0; // 可选择的项目数量
  280. let selectedCount = 0; // 已选择的项目数量
  281. dataSource.forEach((row) => {
  282. const upstreamVal = row.upstreams?.[upName];
  283. // 只有具体数值的才是可选择的(不是null、undefined或"same")
  284. if (upstreamVal !== null && upstreamVal !== undefined && upstreamVal !== 'same') {
  285. selectableCount++;
  286. const isSelected = resolutions[row.model]?.[row.ratioType] === upstreamVal;
  287. if (isSelected) {
  288. selectedCount++;
  289. }
  290. }
  291. });
  292. return {
  293. selectableCount,
  294. selectedCount,
  295. allSelected: selectableCount > 0 && selectedCount === selectableCount,
  296. partiallySelected: selectedCount > 0 && selectedCount < selectableCount,
  297. hasSelectableItems: selectableCount > 0
  298. };
  299. })();
  300. // 处理全选/取消全选
  301. const handleBulkSelect = (checked) => {
  302. setResolutions((prev) => {
  303. const newRes = { ...prev };
  304. dataSource.forEach((row) => {
  305. const upstreamVal = row.upstreams?.[upName];
  306. if (upstreamVal !== null && upstreamVal !== undefined && upstreamVal !== 'same') {
  307. if (checked) {
  308. // 选择该值
  309. if (!newRes[row.model]) newRes[row.model] = {};
  310. newRes[row.model][row.ratioType] = upstreamVal;
  311. } else {
  312. // 取消选择该值
  313. if (newRes[row.model]) {
  314. delete newRes[row.model][row.ratioType];
  315. if (Object.keys(newRes[row.model]).length === 0) {
  316. delete newRes[row.model];
  317. }
  318. }
  319. }
  320. }
  321. });
  322. return newRes;
  323. });
  324. };
  325. return {
  326. title: channelStats.hasSelectableItems ? (
  327. <Checkbox
  328. checked={channelStats.allSelected}
  329. indeterminate={channelStats.partiallySelected}
  330. onChange={(e) => handleBulkSelect(e.target.checked)}
  331. >
  332. {upName}
  333. </Checkbox>
  334. ) : (
  335. <span>{upName}</span>
  336. ),
  337. dataIndex: upName,
  338. render: (_, record) => {
  339. const upstreamVal = record.upstreams?.[upName];
  340. if (upstreamVal === null || upstreamVal === undefined) {
  341. return <Tag color="default" shape="circle">{t('未设置')}</Tag>;
  342. }
  343. if (upstreamVal === 'same') {
  344. return <Tag color="blue" shape="circle">{t('与本地相同')}</Tag>;
  345. }
  346. // 有具体值,可以选择
  347. const isSelected = resolutions[record.model]?.[record.ratioType] === upstreamVal;
  348. return (
  349. <Checkbox
  350. checked={isSelected}
  351. onChange={(e) => {
  352. const isChecked = e.target.checked;
  353. if (isChecked) {
  354. selectValue(record.model, record.ratioType, upstreamVal);
  355. } else {
  356. setResolutions((prev) => {
  357. const newRes = { ...prev };
  358. if (newRes[record.model]) {
  359. delete newRes[record.model][record.ratioType];
  360. if (Object.keys(newRes[record.model]).length === 0) {
  361. delete newRes[record.model];
  362. }
  363. }
  364. return newRes;
  365. });
  366. }
  367. }}
  368. >
  369. {upstreamVal}
  370. </Checkbox>
  371. );
  372. },
  373. };
  374. }),
  375. ];
  376. return (
  377. <Table
  378. columns={columns}
  379. dataSource={getCurrentPageData(dataSource)}
  380. pagination={{
  381. currentPage: currentPage,
  382. pageSize: pageSize,
  383. total: dataSource.length,
  384. showSizeChanger: true,
  385. showQuickJumper: true,
  386. formatPageText: (page) => t('第 {{start}} - {{end}} 条,共 {{total}} 条', {
  387. start: page.currentStart,
  388. end: page.currentEnd,
  389. total: dataSource.length,
  390. }),
  391. pageSizeOptions: ['5', '10', '20', '50'],
  392. onChange: (page, size) => {
  393. setCurrentPage(page);
  394. setPageSize(size);
  395. },
  396. onShowSizeChange: (current, size) => {
  397. setCurrentPage(1);
  398. setPageSize(size);
  399. }
  400. }}
  401. scroll={{ x: 'max-content' }}
  402. size='middle'
  403. loading={loading || syncLoading}
  404. className="rounded-xl overflow-hidden"
  405. />
  406. );
  407. };
  408. // 更新渠道端点
  409. const updateChannelEndpoint = useCallback((channelId, endpoint) => {
  410. setChannelEndpoints(prev => ({ ...prev, [channelId]: endpoint }));
  411. }, []);
  412. return (
  413. <>
  414. <Form.Section text={renderHeader()}>
  415. {renderDifferenceTable()}
  416. </Form.Section>
  417. <ChannelSelectorModal
  418. t={t}
  419. visible={modalVisible}
  420. onCancel={() => setModalVisible(false)}
  421. onOk={confirmChannelSelection}
  422. allChannels={allChannels}
  423. selectedChannelIds={selectedChannelIds}
  424. setSelectedChannelIds={setSelectedChannelIds}
  425. channelEndpoints={channelEndpoints}
  426. updateChannelEndpoint={updateChannelEndpoint}
  427. />
  428. </>
  429. );
  430. }