import {
  useState,
  useEffect,
  Card,
  Tabs,
  Table,
  Button,
  Form,
  Input,
  Select,
  Modal,
  message,
  Space,
  Tag,
  Upload,
  Switch,
  InputNumber,
  Row,
  Col,
  Timeline,
  Badge,
  Popconfirm,
  Tree,
  TreeSelect,
  Tooltip,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SaveOutlined,
  UploadOutlined,
  SyncOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  HistoryOutlined,
  RollbackOutlined,
  UserOutlined,
  FilterOutlined,
  DownOutlined,
  UpOutlined,
  FolderOutlined,
  FileOutlined,
  Option,
  TextArea,
  FC,
} from '@/imports';
import type { UploadProps, TreeProps } from 'antd';
import { settingsDataSource, PlatformAccount, ExchangeRate, CostTemplate, WinNode, ConfigCategory, ConfigChangeLog, Tenant } from '@/services/settingsDataSource';

const SystemSettings: FC = () => {
  const [activeTab, setActiveTab] = useState('platform');
  const [loading, setLoading] = useState(false);
  const [platformAccounts, setPlatformAccounts] = useState<PlatformAccount[]>([]);
  const [exchangeRates, setExchangeRates] = useState<ExchangeRate[]>([]);
  const [costTemplates, setCostTemplates] = useState<CostTemplate[]>([]);
  const [winNodes, setWinNodes] = useState<WinNode[]>([]);
  const [configCategories, setConfigCategories] = useState<ConfigCategory[]>([]);
  const [configChangeLogs, setConfigChangeLogs] = useState<ConfigChangeLog[]>([]);
  const [tenants, setTenants] = useState<Tenant[]>([]);
  
  const [platformModalVisible, setPlatformModalVisible] = useState(false);
  const [rateModalVisible, setRateModalVisible] = useState(false);
  const [templateModalVisible, setTemplateModalVisible] = useState(false);
  const [nodeModalVisible, setNodeModalVisible] = useState(false);
  const [categoryModalVisible, setCategoryModalVisible] = useState(false);
  const [auditModalVisible, setAuditModalVisible] = useState(false);
  const [tenantModalVisible, setTenantModalVisible] = useState(false);
  
  const [editingPlatform, setEditingPlatform] = useState<PlatformAccount | null>(null);
  const [editingRate, setEditingRate] = useState<ExchangeRate | null>(null);
  const [editingTemplate, setEditingTemplate] = useState<CostTemplate | null>(null);
  const [editingNode, setEditingNode] = useState<WinNode | null>(null);
  const [editingCategory, setEditingCategory] = useState<ConfigCategory | null>(null);
  const [editingTenant, setEditingTenant] = useState<Tenant | null>(null);
  
  const [platformForm] = Form.useForm();
  const [rateForm] = Form.useForm();
  const [templateForm] = Form.useForm();
  const [nodeForm] = Form.useForm();
  const [categoryForm] = Form.useForm();
  const [tenantForm] = Form.useForm();
  
  const [selectedTenant, setSelectedTenant] = useState<string>('all'); // 租户筛选

  useEffect(() => {
    fetchPlatformAccounts();
    fetchExchangeRates();
    fetchCostTemplates();
    fetchWinNodes();
    fetchConfigCategories();
    fetchConfigChangeLogs();
    fetchTenants();
  }, []);

  const fetchConfigCategories = async () => {
    setLoading(true);
    setTimeout(() => {
      const mockCategories: ConfigCategory[] = [
        {
          id: '1',
          name: '通用设置',
          key: 'GENERAL',
          description: '系统通用配置项',
          parentId: null,
          order: 1,
          createdAt: '2026-01-01',
        },
        {
          id: '2',
          name: '安全设置',
          key: 'SECURITY',
          description: '系统安全相关配置',
          parentId: null,
          order: 2,
          createdAt: '2026-01-01',
        },
        {
          id: '3',
          name: '通知设置',
          key: 'NOTIFICATION',
          description: '系统通知相关配置',
          parentId: null,
          order: 3,
          createdAt: '2026-01-01',
        },
        {
          id: '4',
          name: '集成设置',
          key: 'INTEGRATION',
          description: '第三方集成相关配置',
          parentId: null,
          order: 4,
          createdAt: '2026-01-01',
        },
        {
          id: '5',
          name: '计费设置',
          key: 'BILLING',
          description: '系统计费相关配置',
          parentId: null,
          order: 5,
          createdAt: '2026-01-01',
        },
      ];
      setConfigCategories(mockCategories);
      setLoading(false);
    }, 500);
  };

  const fetchConfigChangeLogs = async () => {
    setLoading(true);
    setTimeout(() => {
      const mockLogs: ConfigChangeLog[] = [
        {
          id: '1',
          configKey: 'platform.accounts.amazon',
          oldValue: JSON.stringify({ status: 'inactive' }),
          newValue: JSON.stringify({ status: 'active' }),
          changedBy: 'admin',
          changedAt: '2026-03-20 14:30:00',
          reason: '激活Amazon账号',
        },
        {
          id: '2',
          configKey: 'exchange.rates.usd_cny',
          oldValue: '7.20',
          newValue: '7.25',
          changedBy: 'admin',
          changedAt: '2026-03-19 10:15:00',
          reason: '更新汇率',
        },
        {
          id: '3',
          configKey: 'cost.templates.amazon',
          oldValue: JSON.stringify({ platformFee: 15.0 }),
          newValue: JSON.stringify({ platformFee: 14.0 }),
          changedBy: 'admin',
          changedAt: '2026-03-18 09:00:00',
          reason: '调整平台费率',
        },
      ];
      setConfigChangeLogs(mockLogs);
      setLoading(false);
    }, 500);
  };

  const fetchTenants = async () => {
    setLoading(true);
    setTimeout(() => {
      const mockTenants: Tenant[] = [
        {
          id: '1',
          name: '默认租户',
          key: 'default',
          status: 'active',
          plan: 'enterprise',
          createdAt: '2026-01-01',
        },
        {
          id: '2',
          name: '测试租户',
          key: 'test',
          status: 'active',
          plan: 'trial',
          createdAt: '2026-01-10',
        },
        {
          id: '3',
          name: '生产租户',
          key: 'prod',
          status: 'active',
          plan: 'enterprise',
          createdAt: '2026-01-15',
        },
      ];
      setTenants(mockTenants);
      setLoading(false);
    }, 500);
  };

  const handleAddCategory = () => {
    setEditingCategory(null);
    categoryForm.resetFields();
    setCategoryModalVisible(true);
  };

  const handleEditCategory = (record: ConfigCategory) => {
    setEditingCategory(record);
    categoryForm.setFieldsValue(record);
    setCategoryModalVisible(true);
  };

  const handleDeleteCategory = (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个配置分类吗？',
      onOk: () => {
        setConfigCategories(configCategories.filter(cat => cat.id !== id));
        message.success('配置分类已删除');
      },
    });
  };

  const handleCategorySubmit = async (values: any) => {
    setLoading(true);
    setTimeout(() => {
      if (editingCategory) {
        setConfigCategories(configCategories.map(cat => 
          cat.id === editingCategory.id ? { ...cat, ...values } : cat
        ));
        message.success('配置分类已更新');
      } else {
        const newCategory: ConfigCategory = {
          id: Date.now().toString(),
          ...values,
          createdAt: new Date().toISOString().split('T')[0],
        };
        setConfigCategories([...configCategories, newCategory]);
        message.success('配置分类已添加');
      }
      setCategoryModalVisible(false);
      setLoading(false);
    }, 1000);
  };

  const handleAddTenant = () => {
    setEditingTenant(null);
    tenantForm.resetFields();
    setTenantModalVisible(true);
  };

  const handleEditTenant = (record: Tenant) => {
    setEditingTenant(record);
    tenantForm.setFieldsValue(record);
    setTenantModalVisible(true);
  };

  const handleDeleteTenant = (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个租户吗？',
      onOk: () => {
        setTenants(tenants.filter(tenant => tenant.id !== id));
        message.success('租户已删除');
      },
    });
  };

  const handleTenantSubmit = async (values: any) => {
    setLoading(true);
    setTimeout(() => {
      if (editingTenant) {
        setTenants(tenants.map(tenant => 
          tenant.id === editingTenant.id ? { ...tenant, ...values } : tenant
        ));
        message.success('租户已更新');
      } else {
        const newTenant: Tenant = {
          id: Date.now().toString(),
          ...values,
          status: 'active',
          createdAt: new Date().toISOString().split('T')[0],
        };
        setTenants([...tenants, newTenant]);
        message.success('租户已添加');
      }
      setTenantModalVisible(false);
      setLoading(false);
    }, 1000);
  };

  const handleRollbackConfig = (log: ConfigChangeLog) => {
    Modal.confirm({
      title: '确认回滚',
      content: `确定要回滚配置 ${log.configKey} 到之前的值吗？`,
      onOk: () => {
        // 模拟回滚操作
        message.success('配置已回滚');
        fetchConfigChangeLogs();
      },
    });
  };

  const fetchPlatformAccounts = async () => {
    setLoading(true);
    setTimeout(() => {
      const mockAccounts: PlatformAccount[] = [
        {
          id: '1',
          platform: 'AMAZON',
          accountName: 'Amazon US Store',
          accountId: 'amazon_us_001',
          status: 'active',
          shopId: 'shop-001',
          shopName: 'Main Store',
          createdAt: '2026-01-01',
        },
        {
          id: '2',
          platform: 'EBAY',
          accountName: 'eBay UK Store',
          accountId: 'ebay_uk_001',
          status: 'active',
          shopId: 'shop-002',
          shopName: 'UK Store',
          createdAt: '2026-01-05',
        },
      ];
      setPlatformAccounts(mockAccounts);
      setLoading(false);
    }, 500);
  };

  const fetchExchangeRates = async () => {
    setLoading(true);
    setTimeout(() => {
      const mockRates: ExchangeRate[] = [
        {
          id: '1',
          fromCurrency: 'USD',
          toCurrency: 'CNY',
          rate: 7.25,
          source: 'AUTO',

          updatedAt: '2026-03-18',
        },
        {
          id: '2',
          fromCurrency: 'EUR',
          toCurrency: 'USD',
          rate: 1.08,
          source: 'AUTO',

          updatedAt: '2026-03-18',
        },
        {
          id: '3',
          fromCurrency: 'GBP',
          toCurrency: 'USD',
          rate: 1.26,
          source: 'MANUAL',

          updatedAt: '2026-03-18',
        },
      ];
      setExchangeRates(mockRates);
      setLoading(false);
    }, 500);
  };

  const fetchCostTemplates = async () => {
    setLoading(true);
    setTimeout(() => {
      const mockTemplates: CostTemplate[] = [
        {
          id: '1',
          name: 'Amazon US Standard',
          category: 'amazon',
          platform: 'AMAZON',
          costItems: [
            { name: 'Platform Fee', type: 'percentage', value: 15.0, currency: 'USD' },
            { name: 'Shipping Cost', type: 'fixed', value: 5.0, currency: 'USD' },
            { name: 'Packaging Cost', type: 'fixed', value: 1.0, currency: 'USD' },
            { name: 'Handling Cost', type: 'fixed', value: 2.0, currency: 'USD' },
            { name: 'Insurance Cost', type: 'fixed', value: 0.5, currency: 'USD' },
            { name: 'Other Cost', type: 'fixed', value: 1.5, currency: 'USD' },
          ],
          isActive: true,
          createdAt: '2026-01-01',
          updatedAt: '2026-03-18',
        },
        {
          id: '2',
          name: 'eBay UK Standard',
          category: 'ebay',
          platform: 'EBAY',
          costItems: [
            { name: 'Platform Fee', type: 'percentage', value: 10.0, currency: 'GBP' },
            { name: 'Shipping Cost', type: 'fixed', value: 3.0, currency: 'GBP' },
            { name: 'Packaging Cost', type: 'fixed', value: 0.8, currency: 'GBP' },
            { name: 'Handling Cost', type: 'fixed', value: 1.5, currency: 'GBP' },
            { name: 'Insurance Cost', type: 'fixed', value: 0.3, currency: 'GBP' },
            { name: 'Other Cost', type: 'fixed', value: 1.0, currency: 'GBP' },
          ],
          isActive: true,
          createdAt: '2026-01-05',
          updatedAt: '2026-03-18',
        },
      ];
      setCostTemplates(mockTemplates);
      setLoading(false);
    }, 500);
  };

  const fetchWinNodes = async () => {
    setLoading(true);
    setTimeout(() => {
      const mockNodes: WinNode[] = [
        {
          id: '1',
          name: 'WinNode-001',
          platform: 'AMAZON',
          accountId: 'amazon_us_001',
          profileDir: 'C:/Profiles/WinNode-001',
          proxy: { host: 'proxy1.example.com', port: 8080, type: 'http' },
          fingerprintPolicy: {
            userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
            timezone: 'America/New_York',
            language: 'en-US',
            screenResolution: '1920x1080',
            webgl: 'NVIDIA GeForce GTX 1080',
          },
          maxConcurrent: 5,
          status: 'ONLINE',
          lastHeartbeat: '2026-03-18 12:30:00',
          createdAt: '2026-01-01',
        },
        {
          id: '2',
          name: 'WinNode-002',
          platform: 'EBAY',
          accountId: 'ebay_us_001',
          profileDir: 'C:/Profiles/WinNode-002',
          proxy: { host: 'proxy2.example.com', port: 8080, type: 'http' },
          fingerprintPolicy: {
            userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
            timezone: 'America/New_York',
            language: 'en-US',
            screenResolution: '1920x1080',
            webgl: 'NVIDIA GeForce GTX 1080',
          },
          maxConcurrent: 3,
          status: 'BUSY',
          lastHeartbeat: '2026-03-18 12:28:00',
          createdAt: '2026-01-10',
        },
      ];
      setWinNodes(mockNodes);
      setLoading(false);
    }, 500);
  };

  const handleAddPlatform = () => {
    setEditingPlatform(null);
    platformForm.resetFields();
    setPlatformModalVisible(true);
  };

  const handleEditPlatform = (record: PlatformAccount) => {
    setEditingPlatform(record);
    platformForm.setFieldsValue(record);
    setPlatformModalVisible(true);
  };

  const handleDeletePlatform = (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个平台账号吗？',
      onOk: () => {
        setPlatformAccounts(platformAccounts.filter(acc => acc.id !== id));
        message.success('平台账号已删除');
      },
    });
  };

  const handleSyncPlatform = (id: string) => {
    message.loading('正在同步...', 0);
    setTimeout(() => {
      message.destroy();
      message.success('同步成功');
      fetchPlatformAccounts();
    }, 2000);
  };

  const handlePlatformSubmit = async (values: any) => {
    setLoading(true);
    setTimeout(() => {
      if (editingPlatform) {
        setPlatformAccounts(platformAccounts.map(acc => 
          acc.id === editingPlatform.id ? { ...acc, ...values } : acc
        ));
        message.success('平台账号已更新');
      } else {
        const newAccount: PlatformAccount = {
          id: Date.now().toString(),
          ...values,
          status: 'active',
          lastSync: new Date().toLocaleString('zh-CN'),
          shopId: 'shop-new',
          shopName: 'New Shop',
          createdAt: new Date().toISOString().split('T')[0],
          updatedAt: new Date().toISOString().split('T')[0],
        };
        setPlatformAccounts([...platformAccounts, newAccount]);
        message.success('平台账号已添加');
      }
      setPlatformModalVisible(false);
      setLoading(false);
    }, 1000);
  };

  const handleAddRate = () => {
    setEditingRate(null);
    rateForm.resetFields();
    setRateModalVisible(true);
  };

  const handleEditRate = (record: ExchangeRate) => {
    setEditingRate(record);
    rateForm.setFieldsValue(record);
    setRateModalVisible(true);
  };

  const handleDeleteRate = (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个汇率配置吗？',
      onOk: () => {
        setExchangeRates(exchangeRates.filter(rate => rate.id !== id));
        message.success('汇率配置已删除');
      },
    });
  };

  const handleSyncRates = () => {
    message.loading('正在同步汇率...', 0);
    setTimeout(() => {
      message.destroy();
      message.success('汇率同步成功');
      fetchExchangeRates();
    }, 2000);
  };

  const handleRateSubmit = async (values: any) => {
    setLoading(true);
    setTimeout(() => {
      if (editingRate) {
        setExchangeRates(exchangeRates.map(rate => 
          rate.id === editingRate.id ? { ...rate, ...values } : rate
        ));
        message.success('汇率配置已更新');
      } else {
        const newRate: ExchangeRate = {
          id: Date.now().toString(),
          ...values,
          lastUpdated: new Date().toLocaleString('zh-CN'),
          updatedAt: new Date().toISOString().split('T')[0],
        };
        setExchangeRates([...exchangeRates, newRate]);
        message.success('汇率配置已添加');
      }
      setRateModalVisible(false);
      setLoading(false);
    }, 1000);
  };

  const handleAddTemplate = () => {
    setEditingTemplate(null);
    templateForm.resetFields();
    setTemplateModalVisible(true);
  };

  const handleEditTemplate = (record: CostTemplate) => {
    setEditingTemplate(record);
    templateForm.setFieldsValue(record);
    setTemplateModalVisible(true);
  };

  const handleDeleteTemplate = (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个成本模板吗？',
      onOk: () => {
        setCostTemplates(costTemplates.filter(tpl => tpl.id !== id));
        message.success('成本模板已删除');
      },
    });
  };

  const handleTemplateSubmit = async (values: any) => {
    setLoading(true);
    setTimeout(() => {
      if (editingTemplate) {
        setCostTemplates(costTemplates.map(tpl => 
          tpl.id === editingTemplate.id ? { ...tpl, ...values } : tpl
        ));
        message.success('成本模板已更新');
      } else {
        const newTemplate: CostTemplate = {
          id: Date.now().toString(),
          ...values,
          isActive: true,
          createdAt: new Date().toISOString().split('T')[0],
          updatedAt: new Date().toISOString().split('T')[0],
        };
        setCostTemplates([...costTemplates, newTemplate]);
        message.success('成本模板已添加');
      }
      setTemplateModalVisible(false);
      setLoading(false);
    }, 1000);
  };

  const handleAddNode = () => {
    setEditingNode(null);
    nodeForm.resetFields();
    setNodeModalVisible(true);
  };

  const handleEditNode = (record: WinNode) => {
    setEditingNode(record);
    nodeForm.setFieldsValue(record);
    setNodeModalVisible(true);
  };

  const handleDeleteNode = (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个WinNode节点吗？',
      onOk: () => {
        setWinNodes(winNodes.filter(node => node.id !== id));
        message.success('WinNode节点已删除');
      },
    });
  };

  const handleNodeSubmit = async (values: any) => {
    setLoading(true);
    setTimeout(() => {
      if (editingNode) {
        setWinNodes(winNodes.map(node => 
          node.id === editingNode.id ? { ...node, ...values } : node
        ));
        message.success('WinNode节点已更新');
      } else {
        const newNode: WinNode = {
          id: Date.now().toString(),
          ...values,
          status: 'ONLINE',
          lastHeartbeat: new Date().toLocaleString('zh-CN'),
          createdAt: new Date().toISOString().split('T')[0],
          updatedAt: new Date().toISOString().split('T')[0],
        };
        setWinNodes([...winNodes, newNode]);
        message.success('WinNode节点已添加');
      }
      setNodeModalVisible(false);
      setLoading(false);
    }, 1000);
  };

  const platformColumns = [
    {
      title: '平台',
      dataIndex: 'platform',
      key: 'platform',
      render: (platform: string) => {
        const platformMap: { [key: string]: string } = {
          AMAZON: 'Amazon',
          EBAY: 'eBay',
          SHOPIFY: 'Shopify',
          SHOPEE: 'Shopee',
          LAZADA: 'Lazada',
        };
        return platformMap[platform] || platform;
      },
    },
    {
      title: '账号名称',
      dataIndex: 'accountName',
      key: 'accountName',
    },
    {
      title: 'Seller ID',
      dataIndex: 'sellerId',
      key: 'sellerId',
    },
    {
      title: '市场',
      dataIndex: 'marketplace',
      key: 'marketplace',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap: { [key: string]: { text: string; color: string } } = {
          active: { text: '活跃', color: 'green' },
          inactive: { text: '非活跃', color: 'default' },
          expired: { text: '已过期', color: 'red' },
        };
        const config = statusMap[status] || { text: status, color: 'default' };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '最后同步',
      dataIndex: 'lastSync',
      key: 'lastSync',
    },
    {
      title: '店铺',
      dataIndex: 'shopName',
      key: 'shopName',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: PlatformAccount) => (
        <Space>
          <Button
            type="link"
            icon={<SyncOutlined />}
            onClick={() => handleSyncPlatform(record.id)}
          >
            同步
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEditPlatform(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDeletePlatform(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const rateColumns = [
    {
      title: '源货币',
      dataIndex: 'fromCurrency',
      key: 'fromCurrency',
    },
    {
      title: '目标货币',
      dataIndex: 'toCurrency',
      key: 'toCurrency',
    },
    {
      title: '汇率',
      dataIndex: 'rate',
      key: 'rate',
      render: (rate: number) => rate.toFixed(4),
    },
    {
      title: '来源',
      dataIndex: 'source',
      key: 'source',
      render: (source: string) => {
        const sourceMap: Record<string, { text: string; color: string }> = {
          MANUAL: { text: '手动', color: 'blue' },
          AUTO: { text: '自动', color: 'green' },
        };
        const config = sourceMap[source] || { text: source, color: 'default' };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '最后更新',
      dataIndex: 'lastUpdated',
      key: 'lastUpdated',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: ExchangeRate) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEditRate(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteRate(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const templateColumns = [
    {
      title: '模板名称',
      dataIndex: 'templateName',
      key: 'templateName',
    },
    {
      title: '平台',
      dataIndex: 'platform',
      key: 'platform',
      render: (platform: string) => {
        const platformMap: Record<string, string> = {
          AMAZON: 'Amazon',
          EBAY: 'eBay',
          SHOPIFY: 'Shopify',
          SHOPEE: 'Shopee',
          LAZADA: 'Lazada',
          ALL: '全部',
        };
        return platformMap[platform] || platform;
      },
    },
    {
      title: '平台费(%)',
      dataIndex: 'platformFee',
      key: 'platformFee',
      render: (fee: number) => fee.toFixed(2),
    },
    {
      title: '物流成本',
      dataIndex: 'shippingCost',
      key: 'shippingCost',
      render: (cost: number) => `$${cost.toFixed(2)}`,
    },
    {
      title: '包装成本',
      dataIndex: 'packagingCost',
      key: 'packagingCost',
      render: (cost: number) => `$${cost.toFixed(2)}`,
    },
    {
      title: '状态',
      dataIndex: 'isActive',
      key: 'isActive',
      render: (isActive: boolean) => (
        <Tag color={isActive ? 'green' : 'default'}>
          {isActive ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: CostTemplate) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEditTemplate(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteTemplate(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const nodeColumns = [
    {
      title: '节点名称',
      dataIndex: 'nodeName',
      key: 'nodeName',
    },
    {
      title: 'Profile目录',
      dataIndex: 'profileDir',
      key: 'profileDir',
    },
    {
      title: '代理地址',
      dataIndex: 'proxyUrl',
      key: 'proxyUrl',
    },
    {
      title: '指纹策略',
      dataIndex: 'fingerprintPolicy',
      key: 'fingerprintPolicy',
      render: (policy: string) => {
        const policyMap: Record<string, { text: string; color: string }> = {
          STRICT: { text: '严格', color: 'red' },
          MODERATE: { text: '中等', color: 'orange' },
          RELAXED: { text: '宽松', color: 'green' },
        };
        const config = policyMap[policy] || { text: policy, color: 'default' };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '最大并发',
      dataIndex: 'maxConcurrentTasks',
      key: 'maxConcurrentTasks',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap: Record<string, { text: string; color: string; icon: React.ReactNode }> = {
          ONLINE: { text: '在线', color: 'green', icon: <CheckCircleOutlined /> },
          OFFLINE: { text: '离线', color: 'default', icon: <CloseCircleOutlined /> },
          BUSY: { text: '忙碌', color: 'orange', icon: <ExclamationCircleOutlined /> },
        };
        const config = statusMap[status] || { text: status, color: 'default', icon: null };
        return (
          <Tag color={config.color} icon={config.icon}>
            {config.text}
          </Tag>
        );
      },
    },
    {
      title: '最后心跳',
      dataIndex: 'lastHeartbeat',
      key: 'lastHeartbeat',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: WinNode) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEditNode(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteNode(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="system-settings">
      <div className="page-header">
        <h1>系统设置</h1>
      </div>

      <Card>
        <Tabs 
          activeKey={activeTab} 
          onChange={setActiveTab}
          items={[
            { key: 'platform', label: '平台账号配置', children: (
              <>
                <div style={{ marginBottom: 16 }}>
                  <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={handleAddPlatform}
                  >
                    添加平台账号
                  </Button>
                </div>
                <Table
                  columns={platformColumns}
                  dataSource={platformAccounts}
                  loading={loading}
                  rowKey="id"
                  pagination={{
                    pageSize: 10,
                    showSizeChanger: true,
                  }}
                />
              </>
            )},
            { key: 'rate', label: '汇率配置', children: (
              <>
                <div style={{ marginBottom: 16 }}>
                  <Space>
                    <Button
                      type="primary"
                      icon={<PlusOutlined />}
                      onClick={handleAddRate}
                    >
                      添加汇率
                    </Button>
                    <Button
                      icon={<SyncOutlined />}
                      onClick={handleSyncRates}
                    >
                      同步汇率
                    </Button>
                  </Space>
                </div>
                <Table
                  columns={rateColumns}
                  dataSource={exchangeRates}
                  loading={loading}
                  rowKey="id"
                  pagination={{
                    pageSize: 10,
                    showSizeChanger: true,
                  }}
                />
              </>
            )},
            { key: 'template', label: '成本模板配置', children: (
              <>
                <div style={{ marginBottom: 16 }}>
                  <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={handleAddTemplate}
                  >
                    添加成本模板
                  </Button>
                </div>
                <Table
                  columns={templateColumns}
                  dataSource={costTemplates}
                  loading={loading}
                  rowKey="id"
                  pagination={{
                    pageSize: 10,
                    showSizeChanger: true,
                  }}
                />
              </>
            )},
            { key: 'node', label: 'WinNode配置', children: (
              <>
                <div style={{ marginBottom: 16 }}>
                  <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={handleAddNode}
                  >
                    添加WinNode
                  </Button>
                </div>
                <Table
                  columns={nodeColumns}
                  dataSource={winNodes}
                  loading={loading}
                  rowKey="id"
                  pagination={{
                    pageSize: 10,
                    showSizeChanger: true,
                  }}
                />
              </>
            )},
            { key: 'category', label: '配置分类管理', children: (
              <>
                <div style={{ marginBottom: 16 }}>
                  <Space>
                    <Button
                      type="primary"
                      icon={<PlusOutlined />}
                      onClick={handleAddCategory}
                    >
                      添加配置分类
                    </Button>
                    <Button
                      icon={<SyncOutlined />}
                      onClick={fetchConfigCategories}
                    >
                      刷新分类
                    </Button>
                  </Space>
                </div>
                <Card>
                  <div style={{ marginBottom: 20 }}>
                    <h3>分类层级结构</h3>
                  </div>
                  <Tree
                    defaultExpandedKeys={['1', '2', '3', '4', '5']}
                    treeData={configCategories.map(category => ({
                      title: (
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <span>
                            <FolderOutlined style={{ marginRight: 8 }} />
                            {category.name}
                            <Tag style={{ marginLeft: 8 }}>{category.key}</Tag>
                          </span>
                          <Space size="small">
                            <Button
                              size="small"
                              type="link"
                              icon={<EditOutlined />}
                              onClick={() => handleEditCategory(category)}
                            >
                              编辑
                            </Button>
                            <Button
                              size="small"
                              type="link"
                              danger
                              icon={<DeleteOutlined />}
                              onClick={() => handleDeleteCategory(category.id)}
                            >
                              删除
                            </Button>
                          </Space>
                        </div>
                      ),
                      key: category.id,
                      children: [],
                    }))}
                  />
                </Card>
                <Card style={{ marginTop: 20 }}>
                  <div style={{ marginBottom: 16 }}>
                    <h3>分类列表</h3>
                  </div>
                  <Table
                    columns={[
                      {
                        title: '分类名称',
                        dataIndex: 'name',
                        key: 'name',
                        render: (name: string, record: ConfigCategory) => (
                          <span>
                            <FolderOutlined style={{ marginRight: 8 }} />
                            {name}
                          </span>
                        ),
                      },
                      {
                        title: '分类键',
                        dataIndex: 'key',
                        key: 'key',
                        render: (key: string) => (
                          <Tag>{key}</Tag>
                        ),
                      },
                      {
                        title: '描述',
                        dataIndex: 'description',
                        key: 'description',
                      },
                      {
                        title: '排序',
                        dataIndex: 'order',
                        key: 'order',
                      },
                      {
                        title: '创建时间',
                        dataIndex: 'createdAt',
                        key: 'createdAt',
                      },
                      {
                        title: '操作',
                        key: 'action',
                        render: (_: any, record: ConfigCategory) => (
                          <Space size="small">
                            <Button
                              size="small"
                              type="link"
                              icon={<EditOutlined />}
                              onClick={() => handleEditCategory(record)}
                            >
                              编辑
                            </Button>
                            <Button
                              size="small"
                              type="link"
                              danger
                              icon={<DeleteOutlined />}
                              onClick={() => handleDeleteCategory(record.id)}
                            >
                              删除
                            </Button>
                          </Space>
                        ),
                      },
                    ]}
                    dataSource={configCategories}
                    loading={loading}
                    rowKey="id"
                    pagination={{
                      pageSize: 10,
                      showSizeChanger: true,
                    }}
                  />
                </Card>
              </>
            )},
            { key: 'audit', label: '配置变更审计', children: (
              <>
                <div style={{ marginBottom: 16 }}>
                  <Space>
                    <Button
                      icon={<HistoryOutlined />}
                      onClick={() => setAuditModalVisible(true)}
                    >
                      查看详细审计日志
                    </Button>
                    <Button
                      icon={<SyncOutlined />}
                      onClick={fetchConfigChangeLogs}
                    >
                      刷新审计日志
                    </Button>
                  </Space>
                </div>
                <Card>
                  <div style={{ marginBottom: 20 }}>
                    <h3>审计日志概览</h3>
                  </div>
                  <Timeline mode="left">
                    {configChangeLogs.map(log => (
                      <Timeline.Item key={log.id} color={log.oldValue !== log.newValue ? 'blue' : 'gray'}>
                        <div>
                          <h4 style={{ marginBottom: 8 }}>
                            <UserOutlined style={{ marginRight: 8 }} />
                            {log.changedBy} 变更了 {log.configKey}
                          </h4>
                          <p style={{ marginBottom: 8 }}>时间: {log.changedAt}</p>
                          <p style={{ marginBottom: 8 }}>原因: {log.reason}</p>
                          <div style={{ marginBottom: 8 }}>
                            <div style={{ marginBottom: 4 }}>
                              <span style={{ fontWeight: 'bold' }}>变更前:</span>
                              <TextArea rows={2} value={log.oldValue} readOnly style={{ marginTop: 4 }} />
                            </div>
                            <div style={{ marginBottom: 4 }}>
                              <span style={{ fontWeight: 'bold' }}>变更后:</span>
                              <TextArea rows={2} value={log.newValue} readOnly style={{ marginTop: 4 }} />
                            </div>
                          </div>
                          <Button
                            type="link"
                            icon={<RollbackOutlined />}
                            onClick={() => handleRollbackConfig(log)}
                          >
                            回滚此变更
                          </Button>
                        </div>
                      </Timeline.Item>
                    ))}
                  </Timeline>
                </Card>
                <Card style={{ marginTop: 20 }}>
                  <div style={{ marginBottom: 16 }}>
                    <h3>审计日志列表</h3>
                  </div>
                  <Table
                    columns={[
                      {
                        title: '配置键',
                        dataIndex: 'configKey',
                        key: 'configKey',
                      },
                      {
                        title: '变更前值',
                        dataIndex: 'oldValue',
                        key: 'oldValue',
                        render: (value: string) => (
                          <Tooltip title={value}>
                            <TextArea rows={2} value={value} readOnly />
                          </Tooltip>
                        ),
                      },
                      {
                        title: '变更后值',
                        dataIndex: 'newValue',
                        key: 'newValue',
                        render: (value: string) => (
                          <Tooltip title={value}>
                            <TextArea rows={2} value={value} readOnly />
                          </Tooltip>
                        ),
                      },
                      {
                        title: '变更人',
                        dataIndex: 'changedBy',
                        key: 'changedBy',
                      },
                      {
                        title: '变更时间',
                        dataIndex: 'changedAt',
                        key: 'changedAt',
                      },
                      {
                        title: '变更原因',
                        dataIndex: 'reason',
                        key: 'reason',
                      },
                      {
                        title: '操作',
                        key: 'action',
                        render: (_: any, record: ConfigChangeLog) => (
                          <Button
                            size="small"
                            type="link"
                            icon={<RollbackOutlined />}
                            onClick={() => handleRollbackConfig(record)}
                          >
                            回滚
                          </Button>
                        ),
                      },
                    ]}
                    dataSource={configChangeLogs}
                    loading={loading}
                    rowKey="id"
                    pagination={{
                      pageSize: 5,
                      showSizeChanger: true,
                    }}
                  />
                </Card>
              </>
            )},
            { key: 'tenant', label: '租户管理', children: (
              <>
                <div style={{ marginBottom: 16 }}>
                  <Space>
                    <Button
                      type="primary"
                      icon={<PlusOutlined />}
                      onClick={handleAddTenant}
                    >
                      添加租户
                    </Button>
                    <Form layout="inline">
                      <Form.Item label="租户筛选">
                        <Select
                          value={selectedTenant}
                          onChange={setSelectedTenant}
                          style={{ width: 200 }}
                        >
                          <Option value="all">全部租户</Option>
                          {tenants.map(tenant => (
                            <Option key={tenant.id} value={tenant.id}>{tenant.name}</Option>
                          ))}
                        </Select>
                      </Form.Item>
                    </Form>
                    <Button
                      icon={<SyncOutlined />}
                      onClick={fetchTenants}
                    >
                      刷新租户
                    </Button>
                  </Space>
                </div>
                <Card>
                  <div style={{ marginBottom: 20 }}>
                    <h3>租户概览</h3>
                  </div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 16 }}>
                    {tenants.map(tenant => (
                      <Card
                        key={tenant.id}
                        size="small"
                        style={{ width: 300 }}
                        extra={
                          <Space size="small">
                            <Button
                              size="small"
                              type="link"
                              icon={<EditOutlined />}
                              onClick={() => handleEditTenant(tenant)}
                            >
                              编辑
                            </Button>
                            <Button
                              size="small"
                              type="link"
                              danger
                              icon={<DeleteOutlined />}
                              onClick={() => handleDeleteTenant(tenant.id)}
                            >
                              删除
                            </Button>
                          </Space>
                        }
                      >
                        <Card.Meta
                          title={
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                              <span>{tenant.name}</span>
                              <Tag color={tenant.status === 'active' ? 'green' : 'default'}>
                                {tenant.status === 'active' ? '活跃' : '禁用'}
                              </Tag>
                            </div>
                          }
                          description={
                            <div>
                              <p>租户键: {tenant.key}</p>
                              <p>创建时间: {tenant.createdAt}</p>
                            </div>
                          }
                        />
                      </Card>
                    ))}
                  </div>
                </Card>
                <Card style={{ marginTop: 20 }}>
                  <div style={{ marginBottom: 16 }}>
                    <h3>租户详细列表</h3>
                  </div>
                  <Table
                    columns={[
                      {
                        title: '租户名称',
                        dataIndex: 'name',
                        key: 'name',
                      },
                      {
                        title: '租户键',
                        dataIndex: 'key',
                        key: 'key',
                        render: (key: string) => (
                          <Tag>{key}</Tag>
                        ),
                      },
                      {
                        title: '状态',
                        dataIndex: 'status',
                        key: 'status',
                        render: (status: string) => (
                          <Tag color={status === 'ACTIVE' ? 'green' : 'default'}>
                            {status === 'ACTIVE' ? '活跃' : '禁用'}
                          </Tag>
                        ),
                      },
                      {
                        title: '创建时间',
                        dataIndex: 'createdAt',
                        key: 'createdAt',
                      },
                      {
                        title: '操作',
                        key: 'action',
                        render: (_: any, record: Tenant) => (
                          <Space size="small">
                            <Button
                              size="small"
                              type="link"
                              icon={<EditOutlined />}
                              onClick={() => handleEditTenant(record)}
                            >
                              编辑
                            </Button>
                            <Button
                              size="small"
                              type="link"
                              danger
                              icon={<DeleteOutlined />}
                              onClick={() => handleDeleteTenant(record.id)}
                            >
                              删除
                            </Button>
                          </Space>
                        ),
                      },
                    ]}
                    dataSource={selectedTenant === 'all' ? tenants : tenants.filter(t => t.id === selectedTenant)}
                    loading={loading}
                    rowKey="id"
                    pagination={{
                      pageSize: 10,
                      showSizeChanger: true,
                    }}
                  />
                </Card>
              </>
            )},
          ]}
        />
      </Card>

      <Modal
        title={editingPlatform ? '编辑平台账号' : '添加平台账号'}
        open={platformModalVisible}
        onCancel={() => setPlatformModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={platformForm}
          layout="vertical"
          onFinish={handlePlatformSubmit}
        >
          <Form.Item
            name="platform"
            label="平台"
            rules={[{ required: true, message: '请选择平台' }]}
          >
            <Select placeholder="请选择平台">
              <Option value="AMAZON">Amazon</Option>
              <Option value="EBAY">eBay</Option>
              <Option value="SHOPIFY">Shopify</Option>
              <Option value="SHOPEE">Shopee</Option>
              <Option value="LAZADA">Lazada</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="accountName"
            label="账号名称"
            rules={[{ required: true, message: '请输入账号名称' }]}
          >
            <Input placeholder="请输入账号名称" />
          </Form.Item>

          <Form.Item
            name="sellerId"
            label="Seller ID"
            rules={[{ required: true, message: '请输入Seller ID' }]}
          >
            <Input placeholder="请输入Seller ID" />
          </Form.Item>

          <Form.Item
            name="accessToken"
            label="Access Token"
            rules={[{ required: true, message: '请输入Access Token' }]}
          >
            <Input.Password placeholder="请输入Access Token" />
          </Form.Item>

          <Form.Item
            name="marketplace"
            label="市场"
            rules={[{ required: true, message: '请选择市场' }]}
          >
            <Select placeholder="请选择市场">
              <Option value="US">US</Option>
              <Option value="UK">UK</Option>
              <Option value="DE">DE</Option>
              <Option value="FR">FR</Option>
              <Option value="JP">JP</Option>
            </Select>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} icon={<SaveOutlined />}>
              保存
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={editingRate ? '编辑汇率配置' : '添加汇率配置'}
        open={rateModalVisible}
        onCancel={() => setRateModalVisible(false)}
        footer={null}
        width={500}
      >
        <Form
          form={rateForm}
          layout="vertical"
          onFinish={handleRateSubmit}
        >
          <Form.Item
            name="fromCurrency"
            label="源货币"
            rules={[{ required: true, message: '请选择源货币' }]}
          >
            <Select placeholder="请选择源货币">
              <Option value="USD">USD</Option>
              <Option value="CNY">CNY</Option>
              <Option value="EUR">EUR</Option>
              <Option value="GBP">GBP</Option>
              <Option value="JPY">JPY</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="toCurrency"
            label="目标货币"
            rules={[{ required: true, message: '请选择目标货币' }]}
          >
            <Select placeholder="请选择目标货币">
              <Option value="USD">USD</Option>
              <Option value="CNY">CNY</Option>
              <Option value="EUR">EUR</Option>
              <Option value="GBP">GBP</Option>
              <Option value="JPY">JPY</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="rate"
            label="汇率"
            rules={[{ required: true, message: '请输入汇率' }]}
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入汇率"
              min={0}
              step={0.0001}
              precision={4}
            />
          </Form.Item>

          <Form.Item
            name="source"
            label="来源"
            rules={[{ required: true, message: '请选择来源' }]}
          >
            <Select placeholder="请选择来源">
              <Option value="MANUAL">手动</Option>
              <Option value="AUTO">自动</Option>
            </Select>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} icon={<SaveOutlined />}>
              保存
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={editingTemplate ? '编辑成本模板' : '添加成本模板'}
        open={templateModalVisible}
        onCancel={() => setTemplateModalVisible(false)}
        footer={null}
        width={700}
      >
        <Form
          form={templateForm}
          layout="vertical"
          onFinish={handleTemplateSubmit}
        >
          <Form.Item
            name="templateName"
            label="模板名称"
            rules={[{ required: true, message: '请输入模板名称' }]}
          >
            <Input placeholder="请输入模板名称" />
          </Form.Item>

          <Form.Item
            name="platform"
            label="平台"
            rules={[{ required: true, message: '请选择平台' }]}
          >
            <Select placeholder="请选择平台">
              <Option value="AMAZON">Amazon</Option>
              <Option value="EBAY">eBay</Option>
              <Option value="SHOPIFY">Shopify</Option>
              <Option value="SHOPEE">Shopee</Option>
              <Option value="LAZADA">Lazada</Option>
              <Option value="ALL">全部</Option>
            </Select>
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="platformFee"
                label="平台费(%)"
                rules={[{ required: true, message: '请输入平台费' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入平台费"
                  min={0}
                  max={100}
                  step={0.1}
                  precision={2}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="shippingCost"
                label="物流成本($)"
                rules={[{ required: true, message: '请输入物流成本' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入物流成本"
                  min={0}
                  step={0.01}
                  precision={2}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="packagingCost"
                label="包装成本($)"
                rules={[{ required: true, message: '请输入包装成本' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入包装成本"
                  min={0}
                  step={0.01}
                  precision={2}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="handlingCost"
                label="处理成本($)"
                rules={[{ required: true, message: '请输入处理成本' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入处理成本"
                  min={0}
                  step={0.01}
                  precision={2}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="insuranceCost"
                label="保险成本($)"
                rules={[{ required: true, message: '请输入保险成本' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入保险成本"
                  min={0}
                  step={0.01}
                  precision={2}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="otherCost"
                label="其他成本($)"
                rules={[{ required: true, message: '请输入其他成本' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入其他成本"
                  min={0}
                  step={0.01}
                  precision={2}
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} icon={<SaveOutlined />}>
              保存
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={editingNode ? '编辑WinNode节点' : '添加WinNode节点'}
        open={nodeModalVisible}
        onCancel={() => setNodeModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={nodeForm}
          layout="vertical"
          onFinish={handleNodeSubmit}
        >
          <Form.Item
            name="nodeName"
            label="节点名称"
            rules={[{ required: true, message: '请输入节点名称' }]}
          >
            <Input placeholder="请输入节点名称" />
          </Form.Item>

          <Form.Item
            name="profileDir"
            label="Profile目录"
            rules={[{ required: true, message: '请输入Profile目录' }]}
          >
            <Input placeholder="请输入Profile目录路径" />
          </Form.Item>

          <Form.Item
            name="proxyUrl"
            label="代理地址"
            rules={[{ required: true, message: '请输入代理地址' }]}
          >
            <Input placeholder="请输入代理地址" />
          </Form.Item>

          <Form.Item
            name="fingerprintPolicy"
            label="指纹策略"
            rules={[{ required: true, message: '请选择指纹策略' }]}
          >
            <Select placeholder="请选择指纹策略">
              <Option value="STRICT">严格</Option>
              <Option value="MODERATE">中等</Option>
              <Option value="RELAXED">宽松</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="maxConcurrentTasks"
            label="最大并发任务数"
            rules={[{ required: true, message: '请输入最大并发任务数' }]}
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入最大并发任务数"
              min={1}
              max={10}
            />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} icon={<SaveOutlined />}>
              保存
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={editingCategory ? '编辑配置分类' : '添加配置分类'}
        open={categoryModalVisible}
        onCancel={() => setCategoryModalVisible(false)}
        footer={null}
        width={500}
      >
        <Form
          form={categoryForm}
          layout="vertical"
          onFinish={handleCategorySubmit}
        >
          <Form.Item
            name="name"
            label="分类名称"
            rules={[{ required: true, message: '请输入分类名称' }]}
          >
            <Input placeholder="请输入分类名称" />
          </Form.Item>

          <Form.Item
            name="key"
            label="分类键"
            rules={[{ required: true, message: '请输入分类键' }]}
          >
            <Input placeholder="请输入分类键" />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
            rules={[{ required: true, message: '请输入描述' }]}
          >
            <TextArea placeholder="请输入分类描述" rows={3} />
          </Form.Item>

          <Form.Item
            name="order"
            label="排序"
            rules={[{ required: true, message: '请输入排序' }]}
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入排序"
              min={1}
              step={1}
            />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} icon={<SaveOutlined />}>
              保存
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="配置变更审计日志"
        open={auditModalVisible}
        onCancel={() => setAuditModalVisible(false)}
        footer={null}
        width={800}
      >
        <Timeline>
          {configChangeLogs.map((log, index) => (
            <Timeline.Item key={index}>
              <div>
                <p><strong>配置键:</strong> {log.configKey}</p>
                <p><strong>变更人:</strong> {log.changedBy}</p>
                <p><strong>变更时间:</strong> {log.changedAt}</p>
                <p><strong>变更原因:</strong> {log.reason}</p>
                <div style={{ marginTop: 8 }}>
                  <p><strong>变更前:</strong></p>
                  <TextArea rows={2} value={log.oldValue} readOnly style={{ marginBottom: 8 }} />
                  <p><strong>变更后:</strong></p>
                  <TextArea rows={2} value={log.newValue} readOnly />
                </div>
                <Button
                  type="link"
                  icon={<RollbackOutlined />}
                  onClick={() => handleRollbackConfig(log)}
                  style={{ marginTop: 8 }}
                >
                  回滚此配置
                </Button>
              </div>
            </Timeline.Item>
          ))}
        </Timeline>
      </Modal>

      <Modal
        title={editingTenant ? '编辑租户' : '添加租户'}
        open={tenantModalVisible}
        onCancel={() => setTenantModalVisible(false)}
        footer={null}
        width={500}
      >
        <Form
          form={tenantForm}
          layout="vertical"
          onFinish={handleTenantSubmit}
        >
          <Form.Item
            name="name"
            label="租户名称"
            rules={[{ required: true, message: '请输入租户名称' }]}
          >
            <Input placeholder="请输入租户名称" />
          </Form.Item>

          <Form.Item
            name="key"
            label="租户键"
            rules={[{ required: true, message: '请输入租户键' }]}
          >
            <Input placeholder="请输入租户键" />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Option value="ACTIVE">活跃</Option>
              <Option value="INACTIVE">禁用</Option>
            </Select>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} icon={<SaveOutlined />}>
              保存
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default SystemSettings;