/*
Copyright (C) 2025 QuantumNous

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

For commercial licensing, please contact support@quantumnous.com
*/

import React, { useState, useCallback, useMemo, useEffect } from 'react';
import {
  Button,
  Table,
  Tag,
  Empty,
  Checkbox,
  Form,
  Input,
  Tooltip,
  Select,
  Modal,
} from '@douyinfe/semi-ui';
import { IconHelpCircle, IconSearch } from '@douyinfe/semi-icons';
import {
  RefreshCcw,
  CheckSquare,
  AlertTriangle,
  CheckCircle,
} from 'lucide-react';
import {
  API,
  showError,
  showSuccess,
  showWarning,
  stringToColor,
} from '../../../helpers';
import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { DEFAULT_ENDPOINT } from '../../../constants';
import { useTranslation } from 'react-i18next';
import {
  IllustrationNoResult,
  IllustrationNoResultDark,
} from '@douyinfe/semi-illustrations';
import ChannelSelectorModal from '../../../components/settings/ChannelSelectorModal';

const OFFICIAL_RATIO_PRESET_ID = -100;
const OFFICIAL_RATIO_PRESET_NAME = '官方倍率预设';
const OFFICIAL_RATIO_PRESET_BASE_URL = 'https://basellm.github.io';
const OFFICIAL_RATIO_PRESET_ENDPOINT =
  '/llm-metadata/api/newapi/ratio_config-v1-base.json';
const MODELS_DEV_PRESET_ID = -101;
const MODELS_DEV_PRESET_NAME = 'models.dev 价格预设';
const MODELS_DEV_PRESET_BASE_URL = 'https://models.dev';
const MODELS_DEV_PRESET_ENDPOINT = 'https://models.dev/api.json';

const CHANNEL_PRICING_OPTION_KEYS = [
  'ChannelModelPrice',
  'ChannelModelRatio',
  'ChannelCompletionRatio',
  'ChannelCacheRatio',
  'ChannelCreateCacheRatio',
  'ChannelModelTierRatio',
  'ChannelCompletionTierRatio',
  'ChannelCacheTierRatio',
  'ChannelCreateCacheTierRatio',
];

/** Option 中 Channel* 嵌套字段键名 → 供应商渠道 PUT 请求体字段名 */
const CHANNEL_EXTRA_OPTION_TO_PAYLOAD = [
  ['ChannelImageRatio', 'ImageRatio'],
  ['ChannelAudioRatio', 'AudioRatio'],
  ['ChannelAudioCompletionRatio', 'AudioCompletionRatio'],
];

const UPSTREAM_NAME_ID_RE = /\((-?\d+)\)\s*$/;
const CHANNEL_SELECTION_KEY_SEPARATOR = '@@';

function isOfficialChannelRecord(record) {
  const id = record?.key ?? record?.value;
  const base = record?._originalData?.base_url || '';
  const name = record?.label || '';
  return (
    id === OFFICIAL_RATIO_PRESET_ID ||
    id === MODELS_DEV_PRESET_ID ||
    base === OFFICIAL_RATIO_PRESET_BASE_URL ||
    base === MODELS_DEV_PRESET_BASE_URL ||
    name === OFFICIAL_RATIO_PRESET_NAME ||
    name === MODELS_DEV_PRESET_NAME
  );
}

function parseUpstreamListChannelId(upstreamDisplayName) {
  const m = String(upstreamDisplayName).match(UPSTREAM_NAME_ID_RE);
  if (!m) return null;
  const n = parseInt(m[1], 10);
  return Number.isNaN(n) ? null : n;
}

function parseNestedOption(json) {
  try {
    const o = JSON.parse(json || '{}');
    return o && typeof o === 'object' && !Array.isArray(o) ? o : {};
  } catch {
    return {};
  }
}

/**
 * extractNestedChannelModelMap 从 Channel* 类 Option（按渠道 id 再嵌套模型名）中读取某一渠道的模型→数值表。
 * @param {string} optionJson
 * @param {string} channelIdStr
 */
function extractNestedChannelModelMap(optionJson, channelIdStr) {
  const root = parseNestedOption(optionJson);
  const scoped = root[channelIdStr];
  return scoped && typeof scoped === 'object' && !Array.isArray(scoped)
    ? scoped
    : {};
}

function ratioTypeToPascal(ratioType) {
  return ratioType
    .split('_')
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join('');
}

function channelOptionKeyForRatioType(ratioType) {
  return `Channel${ratioTypeToPascal(ratioType)}`;
}

function buildResolutionKey(ratioType, srcName, syncMode) {
  return syncMode === 'channel' && srcName
    ? `${ratioType}${CHANNEL_SELECTION_KEY_SEPARATOR}${srcName}`
    : ratioType;
}

function parseResolutionKey(key) {
  const idx = key.indexOf(CHANNEL_SELECTION_KEY_SEPARATOR);
  if (idx === -1) {
    return { ratioType: key, srcNameFromKey: null };
  }
  return {
    ratioType: key.slice(0, idx),
    srcNameFromKey: key.slice(idx + CHANNEL_SELECTION_KEY_SEPARATOR.length),
  };
}

function cloneDeep(obj) {
  return JSON.parse(JSON.stringify(obj));
}

/** 解析勾选的上游列名（兼容 number / string 与上游 JSON 类型差异） */
function findUpstreamColumnName(upMap, value) {
  if (!upMap || value === undefined || value === null) return null;
  const same = (a, b) => {
    if (a === b) return true;
    const na = Number(a);
    const nb = Number(b);
    if (Number.isNaN(na) || Number.isNaN(nb)) return false;
    return na === nb;
  };
  const hit = Object.entries(upMap).find(([_, v]) => same(v, value));
  return hit ? hit[0] : null;
}

function resolutionMatchesUpstream(selected, upstreamVal) {
  if (selected === undefined || selected === null) return false;
  if (selected === upstreamVal) return true;
  const ns = Number(selected);
  const nu = Number(upstreamVal);
  return !Number.isNaN(ns) && !Number.isNaN(nu) && ns === nu;
}

function formatCellNumber(v) {
  if (v === null || v === undefined || v === 'same') return '—';
  if (v && typeof v === 'object') {
    if (Array.isArray(v.segments)) {
      return `${v.segments.length}档`;
    }
    return JSON.stringify(v);
  }
  const n = Number(v);
  if (Number.isNaN(n)) return String(v);
  const r = Math.round(n * 1e6) / 1e6;
  if (Math.abs(r - Math.round(r)) < 1e-9) return String(Math.round(r));
  return String(r)
    .replace(/(\.\d*?[1-9])0+$/, '$1')
    .replace(/\.$/, '');
}

const RATIO_TO_PRICE_FACTOR = 2;
const PRICE_DECIMAL_PLACES = 4;
const RATIO_DECIMAL_PLACES = 6;

function toFiniteNumber(value) {
  const n = Number(value);
  return Number.isFinite(n) ? n : null;
}

function roundToPlaces(value, places) {
  const n = toFiniteNumber(value);
  if (n === null) return null;
  const factor = 10 ** places;
  return Math.round(n * factor) / factor;
}

function normalizeStoredNumber(value, places = RATIO_DECIMAL_PLACES) {
  const rounded = roundToPlaces(value, places);
  if (rounded === null) return null;
  const nearestInt = Math.round(rounded);
  // Absorb floating-point epsilon like 33.000000000008 -> 33.
  if (Math.abs(rounded - nearestInt) < 1e-9) {
    return nearestInt;
  }
  return rounded;
}

function ratioToDisplayPrice(ratio) {
  const n = toFiniteNumber(ratio);
  if (n === null) return null;
  return roundToPlaces(n * RATIO_TO_PRICE_FACTOR, PRICE_DECIMAL_PLACES);
}

function formatPriceNumber(v) {
  if (v === null || v === undefined || v === 'same') return '—';
  const n = roundToPlaces(v, PRICE_DECIMAL_PLACES);
  if (n === null) return String(v);
  if (Math.abs(n - Math.round(n)) < 1e-9) return String(Math.round(n));
  return String(n)
    .replace(/(\.\d*?[1-9])0+$/, '$1')
    .replace(/\.$/, '');
}

function isTierValue(value) {
  return value && typeof value === 'object' && Array.isArray(value.segments);
}

function buildTierSegmentDetails(value) {
  if (!isTierValue(value)) return [];
  return value.segments.map((row, idx) => {
    const price = ratioToDisplayPrice(row?.ratio);
    return {
      range: `${idx === 0 ? 0 : value.segments[idx - 1]?.up_to || 0}～${row?.up_to || '∞'}`,
      price: price === null ? '-' : `$${formatPriceNumber(price)}`,
    };
  });
}

function renderTierValue(value, t, fallback = '—') {
  const segments = buildTierSegmentDetails(value);
  if (segments.length === 0) return fallback;

  return (
    <span className='inline-flex items-center gap-1'>
      <span>
        {segments.length}
        {t('档')}
      </span>
      <Tooltip
        position='top'
        content={
          <div style={{ maxWidth: 280 }}>
            {segments.map((segment) => (
              <div key={`${segment.range}-${segment.price}`}>
                {segment.range}：{segment.price} / 1M tokens
              </div>
            ))}
          </div>
        }
      >
        <IconHelpCircle
          size='small'
          style={{ color: 'var(--semi-color-text-2)', cursor: 'help' }}
        />
      </Tooltip>
    </span>
  );
}

function renderCellValue(value, t) {
  return isTierValue(value) ? renderTierValue(value, t) : formatCellNumber(value);
}

function renderChannelOldNewPair(oldVal, newVal, t) {
  const oldNode = isUnsetOldValue(oldVal)
    ? t('未设置')
    : renderCellValue(oldVal, t);
  const newNode = renderCellValue(newVal, t);

  return (
    <span className='inline-flex items-center gap-1'>
      {oldNode}
      <span>/</span>
      {newNode}
    </span>
  );
}

function formatOldNewPair(oldVal, newVal) {
  return `${formatCellNumber(oldVal)}/${formatCellNumber(newVal)}`;
}

function formatPriceOldNewPair(oldVal, newVal) {
  const formatPriceWithSymbol = (value) => {
    const formatted = formatPriceNumber(value);
    return formatted === '—' ? '—' : `$${formatted}`;
  };
  return `${formatPriceWithSymbol(oldVal)}/${formatPriceWithSymbol(newVal)}`;
}

function isUnsetOldValue(value) {
  const n = toFiniteNumber(value);
  return value === null || value === undefined || n === 0;
}

function formatChannelOldValue(oldVal, formatter) {
  return isUnsetOldValue(oldVal) ? '未设置' : formatter(oldVal);
}

function formatChannelOldNewPair(oldVal, newVal) {
  return `${formatChannelOldValue(oldVal, formatCellNumber)}/${formatCellNumber(newVal)}`;
}

function isTierRatioType(ratioType) {
  return [
    'model_tier_ratio',
    'completion_tier_ratio',
    'cache_tier_ratio',
    'create_cache_tier_ratio',
  ].includes(ratioType);
}

function formatChannelPriceOldNewPair(oldVal, newVal) {
  const formatPriceWithSymbol = (value) => {
    const formatted = formatPriceNumber(value);
    return formatted === '—' ? '—' : `$${formatted}`;
  };
  return `${formatChannelOldValue(oldVal, formatPriceWithSymbol)}/${formatPriceWithSymbol(newVal)}`;
}

/** 是否可勾选同步：存在上游新价且与当前生效价不同 */
function isUpstreamCellSelectable(oldVal, newVal) {
  if (newVal === null || newVal === undefined || newVal === 'same')
    return false;
  if (newVal && typeof newVal === 'object') {
    return !resolutionMatchesUpstream(oldVal, newVal);
  }
  const nu = Number(newVal);
  if (Number.isNaN(nu)) return false;
  if (oldVal === null || oldVal === undefined) return true;
  return !resolutionMatchesUpstream(oldVal, newVal);
}

/** ConflictConfirmModal 固定价格与倍率计费冲突时的二次确认弹窗 */
function ConflictConfirmModal({ t, visible, items, onOk, onCancel }) {
  const isMobile = useIsMobile();
  const columns = [
    { title: t('渠道'), dataIndex: 'channel' },
    { title: t('模型'), dataIndex: 'model' },
    {
      title: t('当前计费'),
      dataIndex: 'current',
      render: (text) => <div style={{ whiteSpace: 'pre-wrap' }}>{text}</div>,
    },
    {
      title: t('修改为'),
      dataIndex: 'newVal',
      render: (text) => <div style={{ whiteSpace: 'pre-wrap' }}>{text}</div>,
    },
  ];

  return (
    <Modal
      title={t('确认冲突项修改')}
      visible={visible}
      onCancel={onCancel}
      onOk={onOk}
      size={isMobile ? 'full-width' : 'large'}
    >
      <Table
        columns={columns}
        dataSource={items}
        pagination={false}
        size='small'
      />
    </Modal>
  );
}

/**
 * UpstreamRatioSync 上游倍率拉取、差异对比与勾选应用同步。
 * @param {object} props
 * @param {object} props.options 与 Ratio 设置相同的 Option 字段（含全局与 Channel* JSON）
 * @param {function} props.refresh 保存成功后刷新
 * @param {boolean} [props.useSupplierPricingSave=false] 为 true 时写入供应商定价表 API，不调用 /api/option
 */
export default function UpstreamRatioSync(props) {
  const { t } = useTranslation();
  const [officialModalVisible, setOfficialModalVisible] = useState(false);
  const [channelModalVisible, setChannelModalVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [syncLoading, setSyncLoading] = useState(false);
  const [syncMode, setSyncMode] = useState(null);
  const isMobile = useIsMobile();

  // 渠道选择相关
  const [allChannels, setAllChannels] = useState([]);
  const [selectedOfficialChannelIds, setSelectedOfficialChannelIds] = useState(
    [],
  );
  const [selectedChannelChannelIds, setSelectedChannelChannelIds] = useState(
    [],
  );

  // 渠道端点配置
  const [channelEndpoints, setChannelEndpoints] = useState({}); // { channelId: endpoint }
  const [channelModelNamesMap, setChannelModelNamesMap] = useState({});

  const officialChannels = useMemo(
    () => allChannels.filter(isOfficialChannelRecord),
    [allChannels],
  );
  const nonOfficialChannels = useMemo(
    () => allChannels.filter((ch) => !isOfficialChannelRecord(ch)),
    [allChannels],
  );

  // 差异数据和测试结果
  const [differences, setDifferences] = useState({});
  const [resolutions, setResolutions] = useState({});

  // 模型管理中已启用的模型名称列表（用于过滤同步结果）
  const [enabledModels, setEnabledModels] = useState([]);

  // 是否已经执行过同步
  const [hasSynced, setHasSynced] = useState(false);

  // 分页相关状态
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // 搜索相关状态
  const [searchKeyword, setSearchKeyword] = useState('');

  // 倍率类型过滤
  const [ratioTypeFilter, setRatioTypeFilter] = useState('');

  // 冲突确认弹窗相关
  const [confirmVisible, setConfirmVisible] = useState(false);
  const [conflictItems, setConflictItems] = useState([]); // {channel, model, current, newVal, ratioType}

  const officialSelectorRef = React.useRef(null);
  const channelSelectorRef = React.useRef(null);

  useEffect(() => {
    API.get('/api/channel/models_enabled')
      .then((res) => {
        if (res?.data?.success) {
          setEnabledModels(res.data.data || []);
        }
      })
      .catch(() => {});
  }, []);

  useEffect(() => {
    setCurrentPage(1);
  }, [ratioTypeFilter, searchKeyword]);

  const fetchAllChannels = async () => {
    setLoading(true);
    try {
      const res = await API.get('/api/ratio_sync/channels');

      if (res.data.success) {
        const channels = res.data.data || [];

        const transferData = channels.map((channel) => ({
          key: channel.id,
          label: channel.name,
          value: channel.id,
          disabled: false,
          _originalData: channel,
        }));

        setAllChannels(transferData);

        // 合并已有 endpoints，避免每次打开弹窗都重置
        setChannelEndpoints((prev) => {
          const merged = { ...prev };
          transferData.forEach((channel) => {
            const id = channel.key;
            const channelType = channel._originalData?.type;
            const isModelsDevPreset =
              channel.id === MODELS_DEV_PRESET_ID ||
              channel.base_url === MODELS_DEV_PRESET_BASE_URL;
            const isOfficialRatioPreset =
              channel.id === OFFICIAL_RATIO_PRESET_ID ||
              channel.base_url === OFFICIAL_RATIO_PRESET_BASE_URL;
            const isOpenRouter = channelType === 20;
            const isTokenFactoryOpen = channelType === 60;
            if (!merged[id]) {
              if (isModelsDevPreset) {
                merged[id] = MODELS_DEV_PRESET_ENDPOINT;
              } else if (isOfficialRatioPreset) {
                merged[id] = OFFICIAL_RATIO_PRESET_ENDPOINT;
              } else if (isTokenFactoryOpen) {
                merged[id] = 'tokenfactoryopen';
              } else if (isOpenRouter) {
                merged[id] = 'openrouter';
              } else {
                merged[id] = DEFAULT_ENDPOINT;
              }
            }
          });
          return merged;
        });
      } else {
        showError(res.data.message);
      }
    } catch (error) {
      showError(t('获取渠道失败：') + error.message);
    } finally {
      setLoading(false);
    }
  };

  const confirmOfficialSelection = () => {
    const selected = officialChannels
      .filter((ch) => selectedOfficialChannelIds.includes(ch.value))
      .map((ch) => ch._originalData);

    if (selected.length === 0) {
      showWarning(t('请至少选择一个渠道'));
      return;
    }

    setOfficialModalVisible(false);
    fetchRatiosFromChannels(selected, 'official');
  };

  const confirmChannelSelection = () => {
    const selected = nonOfficialChannels
      .filter((ch) => selectedChannelChannelIds.includes(ch.value))
      .map((ch) => ch._originalData);

    if (selected.length === 0) {
      showWarning(t('请至少选择一个渠道'));
      return;
    }

    setChannelModalVisible(false);
    fetchRatiosFromChannels(selected, 'channel');
  };

  const fetchRatiosFromChannels = async (channelList, mode) => {
    setSyncLoading(true);

    if (mode === 'channel') {
      await loadChannelModelNamesForChannels(channelList);
    }

    const upstreams = channelList.map((ch) => ({
      id: ch.id,
      name: ch.name,
      base_url: ch.base_url,
      endpoint: channelEndpoints[ch.id] || DEFAULT_ENDPOINT,
    }));

    const payload = {
      upstreams: upstreams,
      timeout: 10,
      sync_mode: mode,
      // 应用同步后再次拉取时仍返回已与上游一致的模型行，避免 differences 被清空
      include_aligned: true,
    };

    try {
      const res = await API.post('/api/ratio_sync/fetch', payload);

      if (!res.data.success) {
        showError(res.data.message || t('后端请求失败'));
        setSyncLoading(false);
        return;
      }

      const { differences = {}, test_results = [] } = res.data.data;

      const errorResults = test_results.filter((r) => r.status === 'error');
      if (errorResults.length > 0) {
        showWarning(
          t('部分渠道测试失败：') +
            errorResults.map((r) => `${r.name}: ${r.error}`).join(', '),
        );
      }

      setDifferences(differences);
      setResolutions({});
      setSyncMode(mode);
      setHasSynced(true);

      if (Object.keys(differences).length === 0) {
        showSuccess(t('未找到差异化倍率，无需同步'));
      }
    } catch (e) {
      showError(t('请求后端接口失败：') + e.message);
    } finally {
      setSyncLoading(false);
    }
  };

  const parseChannelModelNamesFromChannelData = (channelData) => {
    const raw = String(channelData?.models || '').trim();
    if (!raw) return [];
    return Array.from(
      new Set(
        raw
          .split(',')
          .map((name) => name.trim())
          .filter(Boolean),
      ),
    );
  };

  const loadChannelModelNamesForChannels = async (channelList) => {
    const missingChannels = channelList.filter(
      (ch) => !channelModelNamesMap[String(ch.id)],
    );
    if (missingChannels.length === 0) return;

    const results = await Promise.all(
      missingChannels.map(async (ch) => {
        try {
          const res = await API.get(`/api/channel/${ch.id}`, {
            skipErrorHandler: true,
          });
          if (!res?.data?.success) {
            showError(res?.data?.message || t('获取渠道模型列表失败'));
            return [String(ch.id), []];
          }
          return [
            String(ch.id),
            parseChannelModelNamesFromChannelData(res.data.data),
          ];
        } catch (error) {
          showError(error?.message || t('获取渠道模型列表失败'));
          return [String(ch.id), []];
        }
      }),
    );

    setChannelModelNamesMap((prev) => ({
      ...prev,
      ...Object.fromEntries(results),
    }));
  };

  function getBillingCategory(ratioType) {
    return ratioType === 'model_price' ? 'price' : 'ratio';
  }

  const selectValue = useCallback(
    (model, ratioType, value, srcName) => {
      const category = getBillingCategory(ratioType);
      const resolutionKey = buildResolutionKey(ratioType, srcName, syncMode);

      setResolutions((prev) => {
        const newModelRes = { ...(prev[model] || {}) };

        Object.keys(newModelRes).forEach((rt) => {
          const parsed = parseResolutionKey(rt);
          if (getBillingCategory(parsed.ratioType) !== category) {
            delete newModelRes[rt];
          }
        });

        if (syncMode === 'official') {
          Object.keys(newModelRes).forEach((rt) => {
            const parsed = parseResolutionKey(rt);
            if (parsed.ratioType === ratioType) {
              delete newModelRes[rt];
            }
          });
        }

        newModelRes[resolutionKey] = { value, srcName, ratioType };

        return {
          ...prev,
          [model]: newModelRes,
        };
      });
    },
    [setResolutions, syncMode],
  );

  const buildPricingBaseline = useCallback(() => {
    const global = {
      ModelRatio: parseNestedOption(props.options.ModelRatio),
      CompletionRatio: parseNestedOption(props.options.CompletionRatio),
      CacheRatio: parseNestedOption(props.options.CacheRatio),
      CreateCacheRatio: parseNestedOption(props.options.CreateCacheRatio),
      ModelPrice: parseNestedOption(props.options.ModelPrice),
      ModelTierRatio: parseNestedOption(props.options.ModelTierRatio),
      CompletionTierRatio: parseNestedOption(props.options.CompletionTierRatio),
      CacheTierRatio: parseNestedOption(props.options.CacheTierRatio),
      CreateCacheTierRatio: parseNestedOption(props.options.CreateCacheTierRatio),
    };
    const channel = {};
    CHANNEL_PRICING_OPTION_KEYS.forEach((k) => {
      channel[k] = parseNestedOption(props.options[k]);
    });
    return { global, channel };
  }, [props.options]);

  const applySync = async () => {
    const baseline = buildPricingBaseline();

    const conflicts = [];

    const billingCategoryForChannel = (model, channelIdStr, chMaps) => {
      const priceMap = chMaps.ChannelModelPrice[channelIdStr];
      if (priceMap && priceMap[model] !== undefined) return 'price';
      const mr = chMaps.ChannelModelRatio[channelIdStr];
      const cr = chMaps.ChannelCompletionRatio[channelIdStr];
      const cache = chMaps.ChannelCacheRatio[channelIdStr];
      if (
        (mr && mr[model] !== undefined) ||
        (cr && cr[model] !== undefined) ||
        (cache && cache[model] !== undefined)
      )
        return 'ratio';
      return null;
    };

    const billingCategoryGlobal = (model, g) => {
      if (g.ModelPrice[model] !== undefined) return 'price';
      if (
        g.ModelRatio[model] !== undefined ||
        g.CompletionRatio[model] !== undefined ||
        g.CacheRatio[model] !== undefined
      )
        return 'ratio';
      return null;
    };

    Object.entries(resolutions).forEach(([model, ratios]) => {
      const groups = new Map();
      Object.entries(ratios).forEach(([resKey, res]) => {
        const parsed = parseResolutionKey(resKey);
        const ratioType = res.ratioType || parsed.ratioType;
        const src = res.srcName || parsed.srcNameFromKey;
        const value = res.value;
        const cid =
          syncMode === 'channel' ? parseUpstreamListChannelId(src) : null;
        const tkey = cid != null && cid > 0 ? `channel:${cid}` : 'global';
        if (!groups.has(tkey)) {
          groups.set(tkey, { cid, ratios: {}, srcNames: {} });
        }
        groups.get(tkey).ratios[ratioType] = value;
        groups.get(tkey).srcNames[ratioType] = src;
      });

      groups.forEach(({ cid, ratios: r, srcNames }) => {
        const newCat = 'model_price' in r ? 'price' : 'ratio';
        const localCat =
          cid != null && cid > 0
            ? billingCategoryForChannel(model, String(cid), baseline.channel)
            : billingCategoryGlobal(model, baseline.global);

        if (localCat && localCat !== newCat) {
          let currentDesc = '';
          if (cid != null && cid > 0) {
            const idStr = String(cid);
            if (localCat === 'price') {
              currentDesc = `${t('固定价格')} : ${baseline.channel.ChannelModelPrice[idStr]?.[model]}`;
            } else {
              currentDesc = `${t('模型倍率')} : ${baseline.channel.ChannelModelRatio[idStr]?.[model] ?? '-'}\n${t('输出倍率')} : ${baseline.channel.ChannelCompletionRatio[idStr]?.[model] ?? '-'}`;
            }
          } else if (localCat === 'price') {
            currentDesc = `${t('固定价格')} : ${baseline.global.ModelPrice[model]}`;
          } else {
            currentDesc = `${t('模型倍率')} : ${baseline.global.ModelRatio[model] ?? '-'}\n${t('输出倍率')} : ${baseline.global.CompletionRatio[model] ?? '-'}`;
          }

          let newDesc = '';
          if (newCat === 'price') {
            newDesc = `${t('固定价格')} : ${r['model_price']}`;
          } else {
            const newModelRatio = r['model_ratio'] ?? '-';
            const newCompRatio = r['completion_ratio'] ?? '-';
            newDesc = `${t('模型倍率')} : ${newModelRatio}\n${t('输出倍率')} : ${newCompRatio}`;
          }

          const channels = Object.keys(r)
            .map((rt) => srcNames[rt])
            .filter((v, idx, arr) => arr.indexOf(v) === idx)
            .join(', ');

          conflicts.push({
            channel: channels,
            model,
            current: currentDesc,
            newVal: newDesc,
          });
        }
      });
    });

    if (conflicts.length > 0) {
      setConflictItems(conflicts);
      setConfirmVisible(true);
      return;
    }

    await performSync(baseline);
  };

  const performSync = useCallback(
    async (baseline) => {
      const finalRatios = {
        ModelRatio: { ...baseline.global.ModelRatio },
        CompletionRatio: { ...baseline.global.CompletionRatio },
        CacheRatio: { ...baseline.global.CacheRatio },
        CreateCacheRatio: { ...baseline.global.CreateCacheRatio },
        ModelPrice: { ...baseline.global.ModelPrice },
        ModelTierRatio: { ...baseline.global.ModelTierRatio },
        CompletionTierRatio: { ...baseline.global.CompletionTierRatio },
        CacheTierRatio: { ...baseline.global.CacheTierRatio },
        CreateCacheTierRatio: { ...baseline.global.CreateCacheTierRatio },
      };

      const finalChannel = {};
      CHANNEL_PRICING_OPTION_KEYS.forEach((k) => {
        finalChannel[k] = cloneDeep(baseline.channel[k] || {});
      });

      const getCurrentEffectiveModelRatio = (model, cid) => {
        if (cid != null && cid > 0) {
          const channelRatio =
            baseline.channel.ChannelModelRatio?.[String(cid)]?.[model];
          const channelRatioNum = toFiniteNumber(channelRatio);
          if (channelRatioNum !== null) {
            return channelRatioNum;
          }
        }
        return toFiniteNumber(baseline.global.ModelRatio?.[model]);
      };

      const normalizeRatioSelection = (model, cid, rawRatios) => {
        const normalized = { ...rawRatios };
        const selectedModelRatio = toFiniteNumber(normalized.model_ratio);

        let effectiveModelRatio = selectedModelRatio;
        if (effectiveModelRatio !== null) {
          const normalizedInputPrice = ratioToDisplayPrice(effectiveModelRatio);
          if (normalizedInputPrice !== null) {
            effectiveModelRatio = roundToPlaces(
              normalizedInputPrice / RATIO_TO_PRICE_FACTOR,
              RATIO_DECIMAL_PLACES,
            );
            normalized.model_ratio = effectiveModelRatio;
          }
        } else {
          effectiveModelRatio = getCurrentEffectiveModelRatio(model, cid);
        }

        const selectedCompletionRatio = toFiniteNumber(
          normalized.completion_ratio,
        );
        if (
          selectedCompletionRatio !== null &&
          effectiveModelRatio !== null &&
          effectiveModelRatio > 0
        ) {
          const normalizedOutputPrice = ratioToDisplayPrice(
            effectiveModelRatio * selectedCompletionRatio,
          );
          if (normalizedOutputPrice !== null) {
            const inputPrice = effectiveModelRatio * RATIO_TO_PRICE_FACTOR;
            if (inputPrice > 0) {
              normalized.completion_ratio = roundToPlaces(
                normalizedOutputPrice / inputPrice,
                RATIO_DECIMAL_PLACES,
              );
            }
          }
        }

        return normalized;
      };

      Object.entries(resolutions).forEach(([model, ratios]) => {
        const groups = new Map();
        Object.entries(ratios).forEach(([resKey, res]) => {
          const parsed = parseResolutionKey(resKey);
          const ratioType = res.ratioType || parsed.ratioType;
          const src = res.srcName || parsed.srcNameFromKey;
          const value = res.value;
          const cid =
            syncMode === 'channel' ? parseUpstreamListChannelId(src) : null;
          const tkey = cid != null && cid > 0 ? `channel:${cid}` : 'global';
          if (!groups.has(tkey)) {
            groups.set(tkey, { cid, ratios: {} });
          }
          groups.get(tkey).ratios[ratioType] = value;
        });

        groups.forEach(({ cid, ratios: r }) => {
          const normalizedRatios = normalizeRatioSelection(model, cid, r);
          const selectedTypes = Object.keys(normalizedRatios);
          const hasPrice = selectedTypes.includes('model_price');
          const hasRatio = selectedTypes.some(
            (rt) => rt !== 'model_price' && 
                   rt !== 'model_tier_ratio' &&
                   rt !== 'completion_tier_ratio' &&
                   rt !== 'cache_tier_ratio' &&
                   rt !== 'create_cache_tier_ratio',
          );

          if (cid != null && cid > 0) {
            const idStr = String(cid);
            if (hasPrice) {
              [
                'ChannelModelRatio',
                'ChannelCompletionRatio',
                'ChannelCacheRatio',
                'ChannelCreateCacheRatio',
              ].forEach((rk) => {
                if (finalChannel[rk][idStr]) {
                  delete finalChannel[rk][idStr][model];
                }
              });
            }
            if (hasRatio && finalChannel.ChannelModelPrice[idStr]) {
              delete finalChannel.ChannelModelPrice[idStr][model];
            }

            Object.entries(normalizedRatios).forEach(([ratioType, value]) => {
              const ck = channelOptionKeyForRatioType(ratioType);
              if (!finalChannel[ck][idStr]) finalChannel[ck][idStr] = {};
              finalChannel[ck][idStr][model] = isTierRatioType(ratioType)
                ? value
                : (normalizeStoredNumber(value) ?? value);
            });
          } else {
            if (hasPrice) {
              delete finalRatios.ModelRatio[model];
              delete finalRatios.CompletionRatio[model];
              delete finalRatios.CacheRatio[model];
            }
            if (hasRatio) {
              delete finalRatios.ModelPrice[model];
            }

            Object.entries(normalizedRatios).forEach(([ratioType, value]) => {
              const gk = ratioTypeToPascal(ratioType);
              if (!finalRatios[gk]) finalRatios[gk] = {};
              finalRatios[gk][model] = isTierRatioType(ratioType)
                ? value
                : (normalizeStoredNumber(value) ?? value);
            });
          }
        });
      });

      setLoading(true);
      try {
        const updates = [];
        if (props.useSupplierPricingSave) {
          /** 供应商：全局四维与上游对比有差异则整包 PUT 全局表，避免清空白名单外的模型列 */
          const globalKeysSynced = [
            'ModelRatio',
            'CompletionRatio',
            'CacheRatio',
            'CreateCacheRatio',
            'ModelPrice',
            'ModelTierRatio',
            'CompletionTierRatio',
            'CacheTierRatio',
            'CreateCacheTierRatio',
          ];
          let globalDirty = false;
          globalKeysSynced.forEach((key) => {
            const before = JSON.stringify(baseline.global[key] || {});
            const after = JSON.stringify(finalRatios[key] || {});
            if (before !== after) globalDirty = true;
          });
          if (globalDirty) {
            updates.push(
              API.put('/api/user/supplier/pricing/global', {
                ModelPrice: finalRatios.ModelPrice || {},
                ModelRatio: finalRatios.ModelRatio || {},
                CompletionRatio: finalRatios.CompletionRatio || {},
                CacheRatio: finalRatios.CacheRatio || {},
                CreateCacheRatio: finalRatios.CreateCacheRatio || {},
                ModelTierRatio: finalRatios.ModelTierRatio || {},
                CompletionTierRatio: finalRatios.CompletionTierRatio || {},
                CacheTierRatio: finalRatios.CacheTierRatio || {},
                CreateCacheTierRatio: finalRatios.CreateCacheTierRatio || {},
                ImageRatio: parseNestedOption(props.options.ImageRatio),
                AudioRatio: parseNestedOption(props.options.AudioRatio),
                AudioCompletionRatio: parseNestedOption(
                  props.options.AudioCompletionRatio,
                ),
              }),
            );
          }
          /** 按渠道 id 比较嵌套 map，变更的渠道分别 PUT supplier channel 定价 */
          const channelIdsToSave = new Set();
          CHANNEL_PRICING_OPTION_KEYS.forEach((key) => {
            const beforeMap = baseline.channel[key] || {};
            const afterMap = finalChannel[key] || {};
            const ids = new Set([
              ...Object.keys(beforeMap),
              ...Object.keys(afterMap),
            ]);
            ids.forEach((idStr) => {
              const b = JSON.stringify(beforeMap[idStr] || {});
              const a = JSON.stringify(afterMap[idStr] || {});
              if (b !== a) channelIdsToSave.add(idStr);
            });
          });
          channelIdsToSave.forEach((idStr) => {
            const channelId = parseInt(idStr, 10);
            if (!Number.isFinite(channelId) || channelId <= 0) {
              return;
            }
            const body = {
              ModelPrice: (finalChannel.ChannelModelPrice || {})[idStr] || {},
              ModelRatio: (finalChannel.ChannelModelRatio || {})[idStr] || {},
              CompletionRatio:
                (finalChannel.ChannelCompletionRatio || {})[idStr] || {},
              CacheRatio: (finalChannel.ChannelCacheRatio || {})[idStr] || {},
              CreateCacheRatio:
                (finalChannel.ChannelCreateCacheRatio || {})[idStr] || {},
              ModelTierRatio:
                (finalChannel.ChannelModelTierRatio || {})[idStr] || {},
              CompletionTierRatio:
                (finalChannel.ChannelCompletionTierRatio || {})[idStr] || {},
              CacheTierRatio:
                (finalChannel.ChannelCacheTierRatio || {})[idStr] || {},
              CreateCacheTierRatio:
                (finalChannel.ChannelCreateCacheTierRatio || {})[idStr] || {},
            };
            CHANNEL_EXTRA_OPTION_TO_PAYLOAD.forEach(([optKey, payloadKey]) => {
              body[payloadKey] = extractNestedChannelModelMap(
                props.options[optKey],
                idStr,
              );
            });
            updates.push(
              API.put(`/api/user/supplier/pricing/channel/${channelId}`, body),
            );
          });
        } else {
          const globalKeys = [
            'ModelRatio',
            'CompletionRatio',
            'CacheRatio',
            'CreateCacheRatio',
            'ModelPrice',
            'ModelTierRatio',
            'CompletionTierRatio',
            'CacheTierRatio',
            'CreateCacheTierRatio',
          ];
          globalKeys.forEach((key) => {
            const before = JSON.stringify(baseline.global[key] || {});
            const after = JSON.stringify(finalRatios[key] || {});
            if (before !== after) {
              updates.push(
                API.put('/api/option/', {
                  key,
                  value: JSON.stringify(finalRatios[key], null, 2),
                }),
              );
            }
          });

          CHANNEL_PRICING_OPTION_KEYS.forEach((key) => {
            const before = JSON.stringify(baseline.channel[key] || {});
            const after = JSON.stringify(finalChannel[key] || {});
            if (before !== after) {
              updates.push(
                API.put('/api/option/', {
                  key,
                  value: JSON.stringify(finalChannel[key], null, 2),
                }),
              );
            }
          });
        }

        if (updates.length === 0) {
          showWarning(t('没有需要保存的变更'));
          setLoading(false);
          return;
        }

        const results = await Promise.all(updates);

        if (results.every((res) => res.data.success)) {
          showSuccess(t('同步成功'));
          props.refresh();

          setDifferences((prevDifferences) => {
            const next = cloneDeep(prevDifferences);

            Object.entries(resolutions).forEach(([model, ratios]) => {
              Object.entries(ratios).forEach(([resKey, res]) => {
                const parsed = parseResolutionKey(resKey);
                const ratioType = res.ratioType || parsed.ratioType;
                const diff = next[model]?.[ratioType];
                if (!diff || typeof diff.upstreams !== 'object') return;

                const srcName = res.srcName;
                if (!srcName || !(srcName in diff.upstreams)) return;

                const num = parseFloat(res.value);
                const synced = Number.isNaN(num)
                  ? res.value
                  : (normalizeStoredNumber(num) ?? num);
                if (!diff.upstream_old) diff.upstream_old = {};
                diff.upstream_old[srcName] = synced;
                diff.upstreams[srcName] = synced;

                if (syncMode !== 'channel') {
                  diff.current = synced;
                }
              });
            });

            return next;
          });

          setResolutions({});
        } else {
          showError(t('部分保存失败'));
        }
      } catch (error) {
        showError(t('保存失败'));
      } finally {
        setLoading(false);
      }
    },
    [
      resolutions,
      differences,
      props.refresh,
      props.useSupplierPricingSave,
      props.options,
      t,
      syncMode,
    ],
  );

  const getCurrentPageData = (dataSource) => {
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    return dataSource.slice(startIndex, endIndex);
  };

  const renderHeader = () => (
    <div className='flex flex-col w-full'>
      <div className='flex flex-col md:flex-row justify-between items-center gap-4 w-full'>
        <div className='flex flex-col md:flex-row gap-2 w-full md:w-auto order-2 md:order-1'>
          <Button
            icon={<RefreshCcw size={14} />}
            className='w-full md:w-auto mt-2'
            onClick={() => {
              setOfficialModalVisible(true);
              if (allChannels.length === 0) {
                fetchAllChannels();
              }
            }}
          >
            {t('官方价格同步')}
          </Button>
          <Button
            icon={<RefreshCcw size={14} />}
            className='w-full md:w-auto mt-2'
            onClick={() => {
              setChannelModalVisible(true);
              if (allChannels.length === 0) {
                fetchAllChannels();
              }
            }}
          >
            {t('渠道价格同步')}
          </Button>

          {(() => {
            const hasSelections = Object.keys(resolutions).length > 0;

            return (
              <Button
                icon={<CheckSquare size={14} />}
                type='secondary'
                onClick={applySync}
                disabled={!hasSelections}
                className='w-full md:w-auto mt-2'
              >
                {t('应用同步')}
              </Button>
            );
          })()}

          <div className='flex flex-col sm:flex-row gap-2 w-full md:w-auto mt-2'>
            <Input
              prefix={<IconSearch size={14} />}
              placeholder={t('搜索模型名称')}
              value={searchKeyword}
              onChange={setSearchKeyword}
              className='w-full sm:w-64'
              showClear
            />

            <Select
              placeholder={t('按倍率类型筛选')}
              value={ratioTypeFilter}
              onChange={setRatioTypeFilter}
              className='w-full sm:w-48'
              showClear
              onClear={() => setRatioTypeFilter('')}
            >
              <Select.Option value='model_ratio'>{t('模型倍率')}</Select.Option>
              <Select.Option value='completion_ratio'>
                {t('输出倍率')}
              </Select.Option>
              <Select.Option value='cache_ratio'>{t('缓存倍率')}</Select.Option>
              <Select.Option value='create_cache_ratio'>
                {t('缓存写入倍率')}
              </Select.Option>
              <Select.Option value='model_price'>{t('固定价格')}</Select.Option>
              <Select.Option value='model_tier_ratio'>
                {t('输入阶梯倍率')}
              </Select.Option>
              <Select.Option value='completion_tier_ratio'>
                {t('输出阶梯倍率')}
              </Select.Option>
              <Select.Option value='cache_tier_ratio'>
                {t('缓存读取阶梯倍率')}
              </Select.Option>
              <Select.Option value='create_cache_tier_ratio'>
                {t('缓存写入阶梯倍率')}
              </Select.Option>
            </Select>
          </div>
        </div>
      </div>
      <div className='mt-2 text-xs text-[var(--semi-color-text-2)]'>
        {t('提示：应用同步后，所选倍率将保存到全局模型定价。')}
      </div>
    </div>
  );

  const renderDifferenceTable = () => {
    const getModelRatioForDisplay = (model, upstreamName, mode) => {
      const modelRatioDiff = differences?.[model]?.model_ratio;
      if (!modelRatioDiff) return null;

      if (mode === 'current') {
        return toFiniteNumber(modelRatioDiff.current);
      }

      if (mode === 'old') {
        const upstreamOldVal = modelRatioDiff.upstream_old?.[upstreamName];
        if (upstreamOldVal !== undefined && upstreamOldVal !== null) {
          return toFiniteNumber(upstreamOldVal);
        }
      }

      if (mode === 'new') {
        const upstreamNewVal = modelRatioDiff.upstreams?.[upstreamName];
        if (upstreamNewVal !== undefined && upstreamNewVal !== null) {
          return toFiniteNumber(upstreamNewVal);
        }
      }

      return toFiniteNumber(modelRatioDiff.current);
    };

    const formatCurrentDisplayValue = (record) => {
      if (record.current === null || record.current === undefined) {
        return t('未设置');
      }

      if (record.ratioType === 'model_ratio') {
        const inputPrice = ratioToDisplayPrice(record.current);
        return inputPrice === null
          ? t('未设置')
          : `$${formatPriceNumber(inputPrice)}`;
      }

      if (record.ratioType === 'completion_ratio') {
        const completionRatio = toFiniteNumber(record.current);
        const inputRatio = getModelRatioForDisplay(
          record.model,
          null,
          'current',
        );
        if (completionRatio === null || inputRatio === null) return t('未设置');
        const outputPrice = ratioToDisplayPrice(inputRatio * completionRatio);
        return outputPrice === null
          ? t('未设置')
          : `$${formatPriceNumber(outputPrice)}`;
      }

      if (
        record.ratioType === 'cache_ratio' ||
        record.ratioType === 'create_cache_ratio'
      ) {
        const cacheRatio = toFiniteNumber(record.current);
        const inputRatio = getModelRatioForDisplay(
          record.model,
          null,
          'current',
        );
        if (cacheRatio === null || inputRatio === null) return t('未设置');
        const cachePrice = ratioToDisplayPrice(inputRatio * cacheRatio);
        return cachePrice === null
          ? t('未设置')
          : `$${formatPriceNumber(cachePrice)}`;
      }

      return renderCellValue(record.current, t);
    };

    const formatUpstreamSingleDisplay = (record, upstreamName) => {
      const newVal = record.upstreams?.[upstreamName];

      if (record.ratioType === 'model_ratio') {
        const newPrice = ratioToDisplayPrice(newVal);
        return newPrice === null ? '—' : `$${formatPriceNumber(newPrice)}`;
      }

      if (record.ratioType === 'completion_ratio') {
        const newCompletion = toFiniteNumber(newVal);
        const newInputRatio = getModelRatioForDisplay(
          record.model,
          upstreamName,
          'new',
        );
        const newOutputPrice =
          newCompletion !== null && newInputRatio !== null
            ? ratioToDisplayPrice(newCompletion * newInputRatio)
            : null;
        return newOutputPrice === null
          ? '—'
          : `$${formatPriceNumber(newOutputPrice)}`;
      }

      if (
        record.ratioType === 'cache_ratio' ||
        record.ratioType === 'create_cache_ratio'
      ) {
        const newCacheRatio = toFiniteNumber(newVal);
        const newInputRatio = getModelRatioForDisplay(
          record.model,
          upstreamName,
          'new',
        );
        const newCachePrice =
          newCacheRatio !== null && newInputRatio !== null
            ? ratioToDisplayPrice(newCacheRatio * newInputRatio)
            : null;
        return newCachePrice === null
          ? '—'
          : `$${formatPriceNumber(newCachePrice)}`;
      }

      return renderCellValue(newVal, t);
    };

    const formatUpstreamPairDisplay = (record, upstreamName) => {
      const oldVal =
        syncMode === 'channel'
          ? record.upstream_old?.[upstreamName]
          : record.current;
      const newVal = record.upstreams?.[upstreamName];

      if (syncMode === 'official') {
        return formatUpstreamSingleDisplay(record, upstreamName);
      }

      if (record.ratioType === 'model_ratio') {
        return formatChannelPriceOldNewPair(
          ratioToDisplayPrice(oldVal),
          ratioToDisplayPrice(newVal),
        );
      }

      if (record.ratioType === 'completion_ratio') {
        const currentCompletion = toFiniteNumber(oldVal);
        const newCompletion = toFiniteNumber(newVal);
        const currentInputRatio = getModelRatioForDisplay(
          record.model,
          upstreamName,
          'old',
        );
        const newInputRatio = getModelRatioForDisplay(
          record.model,
          upstreamName,
          'new',
        );
        const currentOutputPrice =
          currentCompletion !== null && currentInputRatio !== null
            ? ratioToDisplayPrice(currentCompletion * currentInputRatio)
            : null;
        const newOutputPrice =
          newCompletion !== null && newInputRatio !== null
            ? ratioToDisplayPrice(newCompletion * newInputRatio)
            : null;
        return formatChannelPriceOldNewPair(currentOutputPrice, newOutputPrice);
      }

      if (
        record.ratioType === 'cache_ratio' ||
        record.ratioType === 'create_cache_ratio'
      ) {
        const currentCacheRatio = toFiniteNumber(oldVal);
        const newCacheRatio = toFiniteNumber(newVal);
        const currentInputRatio = getModelRatioForDisplay(
          record.model,
          upstreamName,
          'old',
        );
        const newInputRatio = getModelRatioForDisplay(
          record.model,
          upstreamName,
          'new',
        );
        const currentCachePrice =
          currentCacheRatio !== null && currentInputRatio !== null
            ? ratioToDisplayPrice(currentCacheRatio * currentInputRatio)
            : null;
        const newCachePrice =
          newCacheRatio !== null && newInputRatio !== null
            ? ratioToDisplayPrice(newCacheRatio * newInputRatio)
            : null;
        return formatChannelPriceOldNewPair(currentCachePrice, newCachePrice);
      }

      return renderChannelOldNewPair(oldVal, newVal, t);
    };

    const dataSource = useMemo(() => {
      const tmp = [];

      const canonicalMap = new Map(
        enabledModels.map((m) => [m.toLowerCase(), m]),
      );
      const filterEnabled = enabledModels.length > 0;
      const channelModelSetMap = Object.fromEntries(
        Object.entries(channelModelNamesMap).map(([channelId, names]) => [
          channelId,
          new Set((names || []).map((name) => name.toLowerCase())),
        ]),
      );

      const filterChannelOwnedUpstreamMap = (modelName, sourceMap) => {
        if (syncMode !== 'channel') return sourceMap;
        const filtered = {};
        Object.entries(sourceMap || {}).forEach(([upName, value]) => {
          const channelId = parseUpstreamListChannelId(upName);
          if (channelId == null) return;
          const modelSet = channelModelSetMap[String(channelId)];
          // 未拉到该渠道的 models 列表（或列表为空）时不按模型名过滤，避免把整表滤空、误判为「无差异」
          if (!modelSet || modelSet.size === 0) {
            filtered[upName] = value;
            return;
          }
          if (!modelSet.has(modelName.toLowerCase())) return;
          filtered[upName] = value;
        });
        return filtered;
      };

      Object.entries(differences).forEach(([model, ratioTypes]) => {
        const canonical = filterEnabled
          ? (canonicalMap.get(model.toLowerCase()) ?? null)
          : model;
        if (canonical === null) return;

        const hasPrice = 'model_price' in ratioTypes;
        const hasOtherRatio = [
          'model_ratio',
          'completion_ratio',
          'cache_ratio',
          'create_cache_ratio',
        ].some((rt) => rt in ratioTypes);
        const billingConflict = hasPrice && hasOtherRatio;

        Object.entries(ratioTypes).forEach(([ratioType, diff]) => {
          const upstreams = filterChannelOwnedUpstreamMap(
            canonical,
            diff.upstreams,
          );
          if (syncMode === 'channel' && Object.keys(upstreams).length === 0) {
            return;
          }
          const upstreamOld = filterChannelOwnedUpstreamMap(
            canonical,
            diff.upstream_old || {},
          );
          const confidence = filterChannelOwnedUpstreamMap(
            canonical,
            diff.confidence || {},
          );

          tmp.push({
            key: `${canonical}_${ratioType}`,
            model: canonical,
            ratioType,
            current: diff.current,
            upstream_old: upstreamOld,
            upstreams,
            confidence,
            billingConflict,
          });
        });
      });

      return tmp;
    }, [channelModelNamesMap, differences, enabledModels, syncMode]);

    const filteredDataSource = useMemo(() => {
      if (!searchKeyword.trim() && !ratioTypeFilter) {
        return dataSource;
      }

      return dataSource.filter((item) => {
        const matchesKeyword =
          !searchKeyword.trim() ||
          item.model.toLowerCase().includes(searchKeyword.toLowerCase().trim());

        const matchesRatioType =
          !ratioTypeFilter || item.ratioType === ratioTypeFilter;

        return matchesKeyword && matchesRatioType;
      });
    }, [dataSource, searchKeyword, ratioTypeFilter]);

    const upstreamNames = useMemo(() => {
      const set = new Set();
      filteredDataSource.forEach((row) => {
        Object.keys(row.upstreams || {}).forEach((name) => set.add(name));
      });
      return Array.from(set);
    }, [filteredDataSource]);

    if (filteredDataSource.length === 0) {
      return (
        <Empty
          image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
          darkModeImage={
            <IllustrationNoResultDark style={{ width: 150, height: 150 }} />
          }
          description={
            searchKeyword.trim()
              ? t('未找到匹配的模型')
              : Object.keys(differences).length === 0
                ? hasSynced
                  ? t('暂无差异化倍率显示')
                  : t('请先选择同步渠道')
                : t('请先选择同步渠道')
          }
          style={{ padding: 30 }}
        />
      );
    }

    const columns = [
      {
        title: t('模型'),
        dataIndex: 'model',
        fixed: 'left',
      },
      {
        title: t('倍率类型'),
        dataIndex: 'ratioType',
        render: (text, record) => {
          const typeMap = {
            model_ratio: t('输入价格（由倍率换算）'),
            completion_ratio: t('输出价格（由倍率换算）'),
            cache_ratio: t('缓存读取价格（由倍率换算）'),
            create_cache_ratio: t('缓存写入价格（由倍率换算）'),
            model_price: t('固定价格'),
            model_tier_ratio: t('输入阶梯价格（由倍率换算）'),
            completion_tier_ratio: t('输出阶梯价格（由倍率换算）'),
            cache_tier_ratio: t('缓存读取阶梯价格（由倍率换算）'),
            create_cache_tier_ratio: t('缓存写入阶梯价格（由倍率换算）'),
          };
          const baseTag = (
            <Tag color={stringToColor(text)} shape='circle'>
              {typeMap[text] || text}
            </Tag>
          );
          if (record?.billingConflict) {
            return (
              <div className='flex items-center gap-1'>
                {baseTag}
                <Tooltip
                  position='top'
                  content={t(
                    '该模型存在固定价格与倍率计费方式冲突，请确认选择',
                  )}
                >
                  <AlertTriangle size={14} className='text-yellow-500' />
                </Tooltip>
              </div>
            );
          }
          return baseTag;
        },
      },
      {
        title: t('置信度'),
        dataIndex: 'confidence',
        render: (_, record) => {
          const allConfident = Object.values(record.confidence || {}).every(
            (v) => v !== false,
          );

          if (allConfident) {
            return (
              <Tooltip content={t('所有上游数据均可信')}>
                <Tag
                  color='green'
                  shape='circle'
                  type='light'
                  prefixIcon={<CheckCircle size={14} />}
                >
                  {t('可信')}
                </Tag>
              </Tooltip>
            );
          } else {
            const untrustedSources = Object.entries(record.confidence || {})
              .filter(([_, isConfident]) => isConfident === false)
              .map(([name]) => name)
              .join(', ');

            return (
              <Tooltip
                content={t('以下上游数据可能不可信：') + untrustedSources}
              >
                <Tag
                  color='yellow'
                  shape='circle'
                  type='light'
                  prefixIcon={<AlertTriangle size={14} />}
                >
                  {t('谨慎')}
                </Tag>
              </Tooltip>
            );
          }
        },
      },
      {
        title: t('官方价格'),
        dataIndex: 'current',
        render: (_, record) => (
          <Tag
            color={
              record.current !== null && record.current !== undefined
                ? 'blue'
                : 'default'
            }
            shape='circle'
          >
            {formatCurrentDisplayValue(record)}
          </Tag>
        ),
      },
      ...upstreamNames.map((upName) => {
        const getSelectableOldValue = (row) =>
          syncMode === 'channel' ? row.upstream_old?.[upName] : row.current;

        const channelStats = (() => {
          let selectableCount = 0;
          let selectedCount = 0;

          filteredDataSource.forEach((row) => {
            const upstreamVal = row.upstreams?.[upName];
            if (
              isUpstreamCellSelectable(getSelectableOldValue(row), upstreamVal)
            ) {
              selectableCount++;
              const resolutionKey = buildResolutionKey(
                row.ratioType,
                upName,
                syncMode,
              );
              const rowRes = resolutions[row.model]?.[resolutionKey];
              const isSelected =
                rowRes?.srcName === upName &&
                resolutionMatchesUpstream(rowRes?.value, upstreamVal);
              if (isSelected) {
                selectedCount++;
              }
            }
          });

          return {
            selectableCount,
            selectedCount,
            allSelected:
              selectableCount > 0 && selectedCount === selectableCount,
            partiallySelected:
              selectedCount > 0 && selectedCount < selectableCount,
            hasSelectableItems: selectableCount > 0,
          };
        })();

        const handleBulkSelect = (checked) => {
          if (checked) {
            filteredDataSource.forEach((row) => {
              const upstreamVal = row.upstreams?.[upName];
              if (
                isUpstreamCellSelectable(
                  getSelectableOldValue(row),
                  upstreamVal,
                )
              ) {
                selectValue(row.model, row.ratioType, upstreamVal, upName);
              }
            });
          } else {
            setResolutions((prev) => {
              const newRes = { ...prev };
              filteredDataSource.forEach((row) => {
                const resolutionKey = buildResolutionKey(
                  row.ratioType,
                  upName,
                  syncMode,
                );
                if (
                  newRes[row.model] &&
                  newRes[row.model][resolutionKey]?.srcName === upName
                ) {
                  delete newRes[row.model][resolutionKey];
                  if (Object.keys(newRes[row.model]).length === 0) {
                    delete newRes[row.model];
                  }
                }
              });
              return newRes;
            });
          }
        };

        return {
          title: channelStats.hasSelectableItems ? (
            <Checkbox
              checked={channelStats.allSelected}
              indeterminate={channelStats.partiallySelected}
              onChange={(e) => handleBulkSelect(e.target.checked)}
            >
              {upName}
            </Checkbox>
          ) : (
            <span>{upName}</span>
          ),
          dataIndex: upName,
          render: (_, record) => {
            const upstreamVal = record.upstreams?.[upName];
            const isConfident = record.confidence?.[upName] !== false;
            const pairText = formatUpstreamPairDisplay(record, upName);

            if (upstreamVal === null || upstreamVal === undefined) {
              return (
                <Tag color='default' shape='circle'>
                  {t('未设置')}
                </Tag>
              );
            }

            const selectable = isUpstreamCellSelectable(
              getSelectableOldValue(record),
              upstreamVal,
            );
            const resolutionKey = buildResolutionKey(
              record.ratioType,
              upName,
              syncMode,
            );
            const cellRes = resolutions[record.model]?.[resolutionKey];
            const isSelected =
              cellRes?.srcName === upName &&
              resolutionMatchesUpstream(cellRes?.value, upstreamVal);

            const hasTierDisplay =
              isTierValue(upstreamVal) ||
              isTierValue(getSelectableOldValue(record));
            const pairContent = (
              <span
                className='font-mono text-sm tabular-nums'
                style={{ letterSpacing: '0.02em' }}
              >
                {pairText}
              </span>
            );
            const pairEl = hasTierDisplay ? (
              pairContent
            ) : (
              <Tooltip content={t('旧价新价对照说明')}>
                {pairContent}
              </Tooltip>
            );

            if (!selectable) {
              return (
                <div className='flex items-center gap-2'>
                  {pairEl}
                  {!isConfident && (
                    <Tooltip
                      position='left'
                      content={t('该数据可能不可信，请谨慎使用')}
                    >
                      <AlertTriangle size={16} className='text-yellow-500' />
                    </Tooltip>
                  )}
                </div>
              );
            }

            return (
              <div className='flex items-center gap-2'>
                <Checkbox
                  checked={isSelected}
                  onChange={(e) => {
                    const isChecked = e.target.checked;
                    if (isChecked) {
                      selectValue(
                        record.model,
                        record.ratioType,
                        upstreamVal,
                        upName,
                      );
                    } else {
                      setResolutions((prev) => {
                        const newRes = { ...prev };
                        if (
                          newRes[record.model] &&
                          newRes[record.model][resolutionKey]?.srcName ===
                            upName
                        ) {
                          delete newRes[record.model][resolutionKey];
                          if (Object.keys(newRes[record.model]).length === 0) {
                            delete newRes[record.model];
                          }
                        }
                        return newRes;
                      });
                    }
                  }}
                >
                  {pairEl}
                </Checkbox>
                {!isConfident && (
                  <Tooltip
                    position='left'
                    content={t('该数据可能不可信，请谨慎使用')}
                  >
                    <AlertTriangle size={16} className='text-yellow-500' />
                  </Tooltip>
                )}
              </div>
            );
          },
        };
      }),
    ];

    return (
      <Table
        columns={columns}
        dataSource={getCurrentPageData(filteredDataSource)}
        pagination={{
          currentPage: currentPage,
          pageSize: pageSize,
          total: filteredDataSource.length,
          showSizeChanger: true,
          showQuickJumper: true,
          pageSizeOptions: ['5', '10', '20', '50'],
          onChange: (page, size) => {
            setCurrentPage(page);
            setPageSize(size);
          },
          onShowSizeChange: (current, size) => {
            setCurrentPage(1);
            setPageSize(size);
          },
        }}
        scroll={{ x: 'max-content' }}
        size='middle'
        loading={loading || syncLoading}
      />
    );
  };

  const updateChannelEndpoint = useCallback((channelId, endpoint) => {
    setChannelEndpoints((prev) => ({ ...prev, [channelId]: endpoint }));
  }, []);

  const handleOfficialModalClose = () => {
    setOfficialModalVisible(false);
    if (officialSelectorRef.current) {
      officialSelectorRef.current.resetPagination();
    }
  };

  const handleChannelModalClose = () => {
    setChannelModalVisible(false);
    if (channelSelectorRef.current) {
      channelSelectorRef.current.resetPagination();
    }
  };

  return (
    <>
      <Form.Section text={renderHeader()}>
        {renderDifferenceTable()}
      </Form.Section>

      <ChannelSelectorModal
        ref={officialSelectorRef}
        t={t}
        visible={officialModalVisible}
        onCancel={handleOfficialModalClose}
        onOk={confirmOfficialSelection}
        allChannels={officialChannels}
        selectedChannelIds={selectedOfficialChannelIds}
        setSelectedChannelIds={setSelectedOfficialChannelIds}
        channelEndpoints={channelEndpoints}
        updateChannelEndpoint={updateChannelEndpoint}
        modalTitle={t('官方价格同步')}
      />
      <ChannelSelectorModal
        ref={channelSelectorRef}
        t={t}
        visible={channelModalVisible}
        onCancel={handleChannelModalClose}
        onOk={confirmChannelSelection}
        allChannels={nonOfficialChannels}
        selectedChannelIds={selectedChannelChannelIds}
        setSelectedChannelIds={setSelectedChannelChannelIds}
        channelEndpoints={channelEndpoints}
        updateChannelEndpoint={updateChannelEndpoint}
        modalTitle={t('渠道价格同步')}
      />

      <ConflictConfirmModal
        t={t}
        visible={confirmVisible}
        items={conflictItems}
        onOk={async () => {
          setConfirmVisible(false);
          await performSync(buildPricingBaseline());
        }}
        onCancel={() => setConfirmVisible(false)}
      />
    </>
  );
}
