import React, { useState, useEffect } from 'react';
import { Card, Tabs, Table, Button, Form, Input, Select, Modal, message, Space, Tag, Upload, Switch, InputNumber, Row, Col } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SaveOutlined, UploadOutlined, SyncOutlined, CheckCircleOutlined, CloseCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { settingsDataSource, PlatformAccount, ExchangeRate, CostTemplate, WinNode } from '@/services/settingsDataSource';

const { Option } = Select;
const { TabPane } = Tabs;
const { TextArea } = Input;

const SystemSettings: React.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 [platformModalVisible, setPlatformModalVisible] = useState(false);
  const [rateModalVisible, setRateModalVisible] = useState(false);
  const [templateModalVisible, setTemplateModalVisible] = useState(false);
  const [nodeModalVisible, setNodeModalVisible] = 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 [platformForm] = Form.useForm();
  const [rateForm] = Form.useForm();
  const [templateForm] = Form.useForm();
  const [nodeForm] = Form.useForm();

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

  const fetchPlatformAccounts = async () => {
    setLoading(true);
    setTimeout(() => {
      const mockAccounts: PlatformAccount[] = [
        {
          id: '1',
          platform: 'AMAZON',
          accountName: 'Amazon US Store',
          sellerId: 'A1X2Y3Z4W5V6U',
          accessToken: 'amzn.mws.xxxx',
          marketplace: 'US',
          status: 'ACTIVE',
          lastSync: '2026-03-18 10:30:00',
          shopId: 'shop-001',
          shopName: 'Main Store',
          createdAt: '2026-01-01',
          updatedAt: '2026-03-18',
        },
        {
          id: '2',
          platform: 'EBAY',
          accountName: 'eBay UK Store',
          sellerId: 'EBAY12345',
          accessToken: 'ebay.auth.xxxx',
          marketplace: 'UK',
          status: 'ACTIVE',
          lastSync: '2026-03-18 09:15:00',
          shopId: 'shop-002',
          shopName: 'UK Store',
          createdAt: '2026-01-05',
          updatedAt: '2026-03-18',
        },
      ];
      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',
          lastUpdated: '2026-03-18 12:00:00',
          updatedAt: '2026-03-18',
        },
        {
          id: '2',
          fromCurrency: 'EUR',
          toCurrency: 'USD',
          rate: 1.08,
          source: 'AUTO',
          lastUpdated: '2026-03-18 12:00:00',
          updatedAt: '2026-03-18',
        },
        {
          id: '3',
          fromCurrency: 'GBP',
          toCurrency: 'USD',
          rate: 1.26,
          source: 'MANUAL',
          lastUpdated: '2026-03-18 10:00:00',
          updatedAt: '2026-03-18',
        },
      ];
      setExchangeRates(mockRates);
      setLoading(false);
    }, 500);
  };

  const fetchCostTemplates = async () => {
    setLoading(true);
    setTimeout(() => {
      const mockTemplates: CostTemplate[] = [
        {
          id: '1',
          templateName: 'Amazon US Standard',
          platform: 'AMAZON',
          platformFee: 15.0,
          shippingCost: 5.0,
          packagingCost: 1.0,
          handlingCost: 2.0,
          insuranceCost: 0.5,
          otherCost: 1.5,
          isActive: true,
          createdAt: '2026-01-01',
          updatedAt: '2026-03-18',
        },
        {
          id: '2',
          templateName: 'eBay UK Standard',
          platform: 'EBAY',
          platformFee: 10.0,
          shippingCost: 3.0,
          packagingCost: 0.8,
          handlingCost: 1.5,
          insuranceCost: 0.3,
          otherCost: 1.0,
          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',
          nodeName: 'WinNode-001',
          profileDir: 'C:/Profiles/WinNode-001',
          proxyUrl: 'http://proxy1.example.com:8080',
          fingerprintPolicy: 'STRICT',
          maxConcurrentTasks: 5,
          status: 'ONLINE',
          lastHeartbeat: '2026-03-18 12:30:00',
          createdAt: '2026-01-01',
          updatedAt: '2026-03-18',
        },
        {
          id: '2',
          nodeName: 'WinNode-002',
          profileDir: 'C:/Profiles/WinNode-002',
          proxyUrl: 'http://proxy2.example.com:8080',
          fingerprintPolicy: 'MODERATE',
          maxConcurrentTasks: 3,
          status: 'BUSY',
          lastHeartbeat: '2026-03-18 12:28:00',
          createdAt: '2026-01-10',
          updatedAt: '2026-03-18',
        },
      ];
      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 = {
          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 = {
          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 = {
          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 = {
          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 = {
          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 = {
          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}>
          <TabPane tab="平台账号配置" key="platform">
            <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,
              }}
            />
          </TabPane>

          <TabPane tab="汇率配置" key="rate">
            <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,
              }}
            />
          </TabPane>

          <TabPane tab="成本模板配置" key="template">
            <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,
              }}
            />
          </TabPane>

          <TabPane tab="WinNode配置" key="node">
            <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,
              }}
            />
          </TabPane>
        </Tabs>
      </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>
    </div>
  );
};

export default SystemSettings;