import TableActionPopconfirm from '@/components/common/table/TableActionPopconfirm'; import TableStatusSwitch from '@/components/common/table/TableStatusSwitch'; import React, { useEffect, useRef, useState } from 'react'; import { Button, Col, Form, Input, InputNumber, Modal, Row, Space, Spin, Table, Tag, Typography, } from '@/components/ui'; import { IconDelete, IconPlus } from '@/components/ui/icons'; import { useTranslation } from 'react-i18next'; import { API, showError, showSuccess } from '../../../helpers'; const OPTION_KEY = 'image.image_resolution_pricing'; const MATCH_MODE_OPTIONS = [ { value: 'exact', label: '精确匹配' }, { value: 'prefix', label: '前缀匹配' }, ]; const RESOLUTION_RULE_OPTIONS = [ { value: 'manual', label: '手工别名', requiredTiers: [], help: '仅按档位 key 和别名匹配;未命中时使用默认档位。', }, { value: 'gpt_image_2', label: 'GPT Image 2', requiredTiers: ['1k', '2k', '4k'], help: '识别官方尺寸及合法自定义宽高,自定义尺寸按总像素向上取档。', }, { value: 'gemini', label: 'Gemini', requiredTiers: ['1k', '2k', '4k'], help: '识别 imageSize、官方比例尺寸及自定义宽高。0.5K 按 1K 档计费。', }, { value: 'seedream_4_0', label: 'Seedream 4.0', requiredTiers: ['1k', '2k', '4k'], help: '按 Seedream 4.0 官方 1K、2K、4K 尺寸和自定义宽高识别。', }, { value: 'seedream_4_5', label: 'Seedream 4.5', requiredTiers: ['2k', '4k'], help: '按 Seedream 4.5 官方 2K、4K 尺寸和自定义宽高识别。', }, { value: 'seedream_5_0_pro', label: 'Seedream 5.0 Pro', requiredTiers: ['1k', '2k'], help: '识别 1K、1.5K、2K,1.5K 按 1K 档计费。', }, { value: 'seedream_5_0_lite', label: 'Seedream 5.0 Lite', requiredTiers: ['2k', '3k', '4k'], help: '按 Seedream 5.0 Lite 官方 2K、3K、4K 尺寸和自定义宽高识别。', }, ]; const emptyTier = () => ({ key: '', label: '', price_per_image: 0, aliases: '', }); const normalize = (value) => String(value || '') .trim() .toLowerCase() .replaceAll(' ', ''); const parsePricing = (value) => { try { const parsed = JSON.parse(value || '[]'); return Array.isArray(parsed) ? parsed : []; } catch { return []; } }; const resolutionRuleOption = (value) => RESOLUTION_RULE_OPTIONS.find((option) => option.value === value) || RESOLUTION_RULE_OPTIONS[0]; export default function SettingImagePricing({ options, refresh }) { const { t } = useTranslation(); const [loading, setLoading] = useState(false); const [configs, setConfigs] = useState([]); const [modalVisible, setModalVisible] = useState(false); const [editingIndex, setEditingIndex] = useState(-1); const [resolutionRule, setResolutionRule] = useState('manual'); const [tierRows, setTierRows] = useState([emptyTier()]); const formRef = useRef(); useEffect(() => { setConfigs(parsePricing(options?.[OPTION_KEY])); }, [options]); const save = async (next) => { setLoading(true); try { const response = await API.put('/api/option/', { key: OPTION_KEY, value: JSON.stringify(next), }); if (!response.data.success) { showError(response.data.message || t('保存失败')); return false; } setConfigs(next); showSuccess(t('保存成功')); refresh(); return true; } catch (error) { showError(error?.response?.data?.message || t('保存失败,请重试')); return false; } finally { setLoading(false); } }; const openAdd = () => { setEditingIndex(-1); setResolutionRule('manual'); setTierRows([emptyTier()]); setModalVisible(true); setTimeout(() => { formRef.current?.setValues({ model_name: '', match_mode: 'exact', resolution_rule: 'manual', default_tier: '', enabled: true, }); }, 0); }; const openEdit = (record, index) => { const nextResolutionRule = record.resolution_rule || 'manual'; setEditingIndex(index); setResolutionRule(nextResolutionRule); setTierRows( (record.tiers || []).map((tier) => ({ key: tier.key || '', label: tier.label || '', price_per_image: tier.price_per_image || 0, aliases: Array.isArray(tier.aliases) ? tier.aliases.join(',') : '', })), ); setModalVisible(true); setTimeout(() => { formRef.current?.setValues({ model_name: record.model_name || '', match_mode: record.match_mode || 'exact', resolution_rule: nextResolutionRule, default_tier: record.default_tier || '', enabled: record.enabled !== false, }); }, 0); }; const updateTier = (index, patch) => { setTierRows((rows) => rows.map((row, rowIndex) => rowIndex === index ? { ...row, ...patch } : row, ), ); }; const buildConfig = (values) => { const modelName = String(values.model_name || '').trim(); if ( configs.some( (config, index) => index !== editingIndex && normalize(config.model_name) === normalize(modelName), ) ) { showError(t('该模型已配置图片分档计费')); return null; } if (tierRows.length === 0 || tierRows.some((row) => !normalize(row.key))) { showError(t('每个档位都必须填写档位 key')); return null; } const tiers = tierRows.map((row) => ({ key: String(row.key).trim(), label: String(row.label || row.key).trim(), price_per_image: Number(row.price_per_image), aliases: String(row.aliases || '') .split(',') .map((alias) => alias.trim()) .filter(Boolean), })); if (tiers.some((tier) => !(tier.price_per_image > 0))) { showError(t('每个档位的每张单价必须大于 0')); return null; } const seen = new Set(); for (const tier of tiers) { for (const matchValue of [tier.key, ...tier.aliases]) { const key = normalize(matchValue); if (seen.has(key)) { showError(t('同一模型内的档位 key 和别名不能重复')); return null; } seen.add(key); } } const selectedRule = values.resolution_rule || 'manual'; const missingTier = resolutionRuleOption(selectedRule).requiredTiers.find( (requiredTier) => !tiers.some((tier) => normalize(tier.key) === requiredTier), ); if (missingTier) { showError(t('当前识别规则要求配置 {{tier}} 档位', { tier: missingTier })); return null; } const defaultTier = String(values.default_tier || tiers[0].key).trim(); if (!tiers.some((tier) => normalize(tier.key) === normalize(defaultTier))) { showError(t('默认档位必须填写一个已有的档位 key')); return null; } return { model_name: modelName, match_mode: values.match_mode || 'exact', resolution_rule: selectedRule, enabled: values.enabled !== false, default_tier: defaultTier, tiers, }; }; const submit = () => { formRef.current ?.validate() .then(async (values) => { const config = buildConfig(values); if (!config) return; const next = [...configs]; if (editingIndex >= 0) { next[editingIndex] = config; } else { next.push(config); } if (await save(next)) setModalVisible(false); }) .catch(() => {}); }; const remove = async (index) => { const next = configs.filter((_, configIndex) => configIndex !== index); return save(next); }; const toggle = async (index, enabled) => { const next = configs.map((config, configIndex) => configIndex === index ? { ...config, enabled } : config, ); await save(next); }; const columns = [ { title: t('模型名称'), dataIndex: 'model_name', key: 'model_name', }, { title: t('匹配方式'), dataIndex: 'match_mode', key: 'match_mode', render: (matchMode) => t(matchMode === 'prefix' ? '前缀匹配' : '精确匹配'), }, { title: t('识别规则'), dataIndex: 'resolution_rule', key: 'resolution_rule', render: (rule) => t(resolutionRuleOption(rule || 'manual').label), }, { title: t('默认档位'), dataIndex: 'default_tier', key: 'default_tier', }, { title: t('分辨率档位'), dataIndex: 'tiers', key: 'tiers', render: (tiers) => ( {(tiers || []).map((tier) => ( {t('{{label}}: ${{price}}/张', { label: tier.label || tier.key, price: tier.price_per_image, })} ))} ), }, { title: t('启用'), dataIndex: 'enabled', key: 'enabled', render: (enabled, _record, index) => ( toggle(index, checked)} aria-label={t('启用图片分档计费')} /> ), }, { title: t('操作'), key: 'action', width: 110, render: (_text, record, index) => ( remove(index)} > ), }, ]; const currentRule = resolutionRuleOption(resolutionRule); return (
{t( '仅已启用且匹配的模型按分辨率档位计费,未配置模型继续使用现有固定价格或模型倍率。单价单位为美元/张,最终费用仍乘分组倍率。', )}
({ ...record, key: `${record.model_name}-${index}`, }))} rowKey='key' pagination={false} empty={t('暂无图片分档计费配置')} /> = 0 ? t('编辑图片定价') : t('添加图片定价')} visible={modalVisible} onOk={submit} onCancel={() => setModalVisible(false)} okText={t('保存')} cancelText={t('取消')} width={760} confirmLoading={loading} >
(formRef.current = formApi)} initValues={{ model_name: '', match_mode: 'exact', resolution_rule: 'manual', default_tier: '', enabled: true, }} >
{MATCH_MODE_OPTIONS.map((option) => ( {t(option.label)} ))} setResolutionRule(value)} extraText={t(currentRule.help)} > {RESOLUTION_RULE_OPTIONS.map((option) => ( {t(option.label)} ))}
{currentRule.requiredTiers.length > 0 ? t('当前规则必须配置档位:{{tiers}}', { tiers: currentRule.requiredTiers.join('、'), }) : t('手工规则可自定义档位 key,并通过别名匹配请求尺寸。')}
{t('别名始终优先于自动识别,可用于覆盖个别尺寸的计费档位。')}
{t('自定义宽高按总像素向上取最近档位,避免低档计费。')}
{t('档位列表')} {tierRows.map((row, index) => (
updateTier(index, { key: value })} /> updateTier(index, { label: value })} /> updateTier(index, { price_per_image: value }) } /> updateTier(index, { aliases: value })} /> ); }