import {
  useState,
  useEffect,
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  Tag,
  Space,
  Popconfirm,
  message,
  Card,
  Tabs,
  Row,
  Col,
  Statistic,
  Descriptions,
  Badge,
  DatePicker,
  InputNumber,
  Switch,
  Tooltip,
  Dropdown,
  Menu,
  Divider,
  Alert,
  Progress,
  Empty,
  Spin,
  Typography,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  GlobalOutlined,
  UserOutlined,
  SettingOutlined,
  ReloadOutlined,
  SearchOutlined,
  FilterOutlined,
  ExportOutlined,
  DashboardOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  BarChartOutlined,
  FileTextOutlined,
  BellOutlined,
  MoreOutlined,
  StopOutlined,
  PlayCircleOutlined,
  Option,
  TabPane,
  RangePicker,
  TextArea,
  Text,
} from '@/imports';
import { saasTenantDataSource } from '../../services/saasTenantDataSource';
import type { SaasTenant, TenantDomain, TenantUser } from '../../services/saasTenantTypes';

interface TenantStats {
  totalTenants: number;
  activeTenants: number;
  suspendedTenants: number;
  trialTenants: number;
  totalUsers: number;
  totalShops: number;
  totalDomains: number;
  storageUsed: number;
  storageTotal: number;
}

interface TenantUsage {
  userId: number;
  shopId: number;
  storageUsed: number;
  apiCalls: number;
  lastActive: Date;
}

interface OperationLog {
  id: string;
  tenantId: string;
  tenantName: string;
  operation: string;
  operator: string;
  timestamp: Date;
  details: string;
}

export default function SaasTenantManage() {
  const [tenants, setTenants] = useState<SaasTenant[]>([]);
  const [filteredTenants, setFilteredTenants] = useState<SaasTenant[]>([]);
  const [loading, setLoading] = useState(false);
  const [stats, setStats] = useState<TenantStats | null>(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [selectedTenant, setSelectedTenant] = useState<SaasTenant | null>(null);
  const [domains, setDomains] = useState<TenantDomain[]>([]);
  const [users, setUsers] = useState<TenantUser[]>([]);
  const [settings, setSettings] = useState<Record<string, string>>({});
  const [usage, setUsage] = useState<TenantUsage | null>(null);
  const [logs, setLogs] = useState<OperationLog[]>([]);
  const [searchText, setSearchText] = useState('');
  const [filters, setFilters] = useState({
    status: '',
    type: '',
    plan: '',
  });
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [form] = Form.useForm();
  const [editForm] = Form.useForm();
  const [domainForm] = Form.useForm();
  const [userForm] = Form.useForm();

  useEffect(() => {
    loadTenants();
    loadStats();
  }, []);

  useEffect(() => {
    filterTenants();
  }, [tenants, searchText, filters]);

  const loadTenants = async () => {
    setLoading(true);
    try {
      const data = await saasTenantDataSource.list();
      setTenants(data);
    } catch (error: any) {
      message.error(error.message || '加载商户列表失败');
    } finally {
      setLoading(false);
    }
  };

  const loadStats = async () => {
    try {
      const data = await saasTenantDataSource.getStats();
      setStats(data);
    } catch (error: any) {
      console.error('加载统计数据失败:', error);
    }
  };

  const filterTenants = () => {
    let filtered = [...tenants];

    if (searchText) {
      filtered = filtered.filter(t => 
        t.code.toLowerCase().includes(searchText.toLowerCase()) ||
        t.name.toLowerCase().includes(searchText.toLowerCase())
      );
    }

    if (filters.status) {
      filtered = filtered.filter(t => t.status === filters.status);
    }

    if (filters.type) {
      filtered = filtered.filter(t => t.type === filters.type);
    }

    if (filters.plan) {
      filtered = filtered.filter(t => t.plan === filters.plan);
    }

    setFilteredTenants(filtered);
  };

  const handleCreate = async () => {
    try {
      const values = await form.validateFields();
      await saasTenantDataSource.create(values);
      message.success('商户创建成功');
      setModalVisible(false);
      form.resetFields();
      loadTenants();
      loadStats();
    } catch (error: any) {
      message.error(error.message || '创建商户失败');
    }
  };

  const handleEdit = async () => {
    if (!selectedTenant) return;
    
    try {
      const values = await editForm.validateFields();
      await saasTenantDataSource.update(selectedTenant.id, values);
      message.success('商户更新成功');
      setEditModalVisible(false);
      editForm.resetFields();
      loadTenants();
      loadStats();
      if (selectedTenant) {
        handleViewTenant(selectedTenant);
      }
    } catch (error: any) {
      message.error(error.message || '更新商户失败');
    }
  };

  const handleViewTenant = async (tenant: SaasTenant) => {
    setSelectedTenant(tenant);
    try {
      const [domainsData, usersData, settingsData, usageData, logsData] = await Promise.all([
        saasTenantDataSource.getDomains(tenant.id),
        saasTenantDataSource.getUsers(tenant.id),
        saasTenantDataSource.getSettings(tenant.id),
        saasTenantDataSource.getUsage(tenant.id),
        saasTenantDataSource.getOperationLogs(tenant.id),
      ]);
      setDomains(domainsData);
      setUsers(usersData);
      setSettings(settingsData);
      setUsage(usageData);
      setLogs(logsData);
    } catch (error: any) {
      message.error(error.message || '加载商户详情失败');
    }
  };

  const handleDelete = async (tenantId: string) => {
    try {
      await saasTenantDataSource.delete(tenantId);
      message.success('商户删除成功');
      loadTenants();
      loadStats();
    } catch (error: any) {
      message.error(error.message || '删除商户失败');
    }
  };

  const handleSuspend = async (tenantId: string) => {
    try {
      await saasTenantDataSource.updateStatus(tenantId, 'SUSPENDED');
      message.success('商户已暂停');
      loadTenants();
      loadStats();
    } catch (error: any) {
      message.error(error.message || '暂停商户失败');
    }
  };

  const handleActivate = async (tenantId: string) => {
    try {
      await saasTenantDataSource.updateStatus(tenantId, 'ACTIVE');
      message.success('商户已激活');
      loadTenants();
      loadStats();
    } catch (error: any) {
      message.error(error.message || '激活商户失败');
    }
  };

  const handleAddDomain = async () => {
    if (!selectedTenant) return;
    
    try {
      const values = await domainForm.validateFields();
      await saasTenantDataSource.addDomain(selectedTenant.id, values.domain, values.type);
      message.success('域名添加成功');
      domainForm.resetFields();
      const updatedDomains = await saasTenantDataSource.getDomains(selectedTenant.id);
      setDomains(updatedDomains);
    } catch (error: any) {
      message.error(error.message || '添加域名失败');
    }
  };

  const handleVerifyDomain = async (domainId: string) => {
    try {
      await saasTenantDataSource.verifyDomain(domainId);
      message.success('域名验证成功');
      if (selectedTenant) {
        const updatedDomains = await saasTenantDataSource.getDomains(selectedTenant.id);
        setDomains(updatedDomains);
      }
    } catch (error: any) {
      message.error(error.message || '验证域名失败');
    }
  };

  const handleSetPrimaryDomain = async (domainId: string) => {
    try {
      await saasTenantDataSource.setPrimaryDomain(domainId);
      message.success('主域名设置成功');
      if (selectedTenant) {
        const updatedDomains = await saasTenantDataSource.getDomains(selectedTenant.id);
        setDomains(updatedDomains);
      }
    } catch (error: any) {
      message.error(error.message || '设置主域名失败');
    }
  };

  const handleDeleteDomain = async (domainId: string) => {
    try {
      await saasTenantDataSource.deleteDomain(domainId);
      message.success('域名删除成功');
      if (selectedTenant) {
        const updatedDomains = await saasTenantDataSource.getDomains(selectedTenant.id);
        setDomains(updatedDomains);
      }
    } catch (error: any) {
      message.error(error.message || '删除域名失败');
    }
  };

  const handleAddUser = async () => {
    if (!selectedTenant) return;
    
    try {
      const values = await userForm.validateFields();
      await saasTenantDataSource.addUser(
        selectedTenant.id,
        values.userId,
        values.role,
        values.permissions || []
      );
      message.success('用户添加成功');
      userForm.resetFields();
      const updatedUsers = await saasTenantDataSource.getUsers(selectedTenant.id);
      setUsers(updatedUsers);
    } catch (error: any) {
      message.error(error.message || '添加用户失败');
    }
  };

  const handleUpdateUserRole = async (userId: string, role: 'ADMIN' | 'MANAGER' | 'OPERATOR' | 'VIEWER') => {
    if (!selectedTenant) return;
    
    try {
      await saasTenantDataSource.updateUserRole(selectedTenant.id, userId, role);
      message.success('用户角色更新成功');
      const updatedUsers = await saasTenantDataSource.getUsers(selectedTenant.id);
      setUsers(updatedUsers);
    } catch (error: any) {
      message.error(error.message || '更新用户角色失败');
    }
  };

  const handleRemoveUser = async (userId: string) => {
    if (!selectedTenant) return;
    
    try {
      await saasTenantDataSource.removeUser(selectedTenant.id, userId);
      message.success('用户移除成功');
      const updatedUsers = await saasTenantDataSource.getUsers(selectedTenant.id);
      setUsers(updatedUsers);
    } catch (error: any) {
      message.error(error.message || '移除用户失败');
    }
  };

  const handleBatchSuspend = async () => {
    try {
      await Promise.all(selectedRowKeys.map(id => 
        saasTenantDataSource.updateStatus(id as string, 'SUSPENDED')
      ));
      message.success(`成功暂停 ${selectedRowKeys.length} 个商户`);
      setSelectedRowKeys([]);
      loadTenants();
      loadStats();
    } catch (error: any) {
      message.error(error.message || '批量暂停失败');
    }
  };

  const handleBatchActivate = async () => {
    try {
      await Promise.all(selectedRowKeys.map(id => 
        saasTenantDataSource.updateStatus(id as string, 'ACTIVE')
      ));
      message.success(`成功激活 ${selectedRowKeys.length} 个商户`);
      setSelectedRowKeys([]);
      loadTenants();
      loadStats();
    } catch (error: any) {
      message.error(error.message || '批量激活失败');
    }
  };

  const handleExport = async () => {
    try {
      await saasTenantDataSource.exportTenants(filteredTenants);
      message.success('数据导出成功');
    } catch (error: any) {
      message.error(error.message || '导出失败');
    }
  };

  const columns = [
    {
      title: '商户代码',
      dataIndex: 'code',
      key: 'code',
      render: (code: string) => <Tag color="blue">{code}</Tag>,
    },
    {
      title: '商户名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => {
        const colorMap: Record<string, string> = {
          SAAS: 'green',
          ENTERPRISE: 'purple',
          TRIAL: 'orange',
        };
        return <Tag color={colorMap[type]}>{type}</Tag>;
      },
    },
    {
      title: '套餐',
      dataIndex: 'plan',
      key: 'plan',
      render: (plan: string) => {
        const colorMap: Record<string, string> = {
          BASIC: 'default',
          PRO: 'blue',
          ENTERPRISE: 'gold',
        };
        return <Tag color={colorMap[plan]}>{plan}</Tag>;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap: Record<string, { color: string; text: string }> = {
          ACTIVE: { color: 'success', text: '活跃' },
          SUSPENDED: { color: 'warning', text: '暂停' },
          CANCELED: { color: 'error', text: '已取消' },
        };
        const { color, text } = statusMap[status] || { color: 'default', text: status };
        return <Badge status={color as any} text={text} />;
      },
    },
    {
      title: '用户数',
      dataIndex: 'maxUsers',
      key: 'maxUsers',
    },
    {
      title: '店铺数',
      dataIndex: 'maxShops',
      key: 'maxShops',
    },
    {
      title: '存储配额',
      dataIndex: 'storageQuota',
      key: 'storageQuota',
      render: (quota: number) => `${quota} MB`,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date: Date) => new Date(date).toLocaleString('zh-CN'),
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      render: (_: any, record: SaasTenant) => (
        <Space size="small">
          <Tooltip title="管理">
            <Button
              type="link"
              size="small"
              icon={<GlobalOutlined />}
              onClick={() => handleViewTenant(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => {
                setSelectedTenant(record);
                editForm.setFieldsValue(record);
                setEditModalVisible(true);
              }}
            />
          </Tooltip>
          {record.status === 'ACTIVE' ? (
            <Tooltip title="暂停">
              <Button
                type="link"
                size="small"
                icon={<StopOutlined />}
                onClick={() => handleSuspend(record.id)}
              />
            </Tooltip>
          ) : (
            <Tooltip title="激活">
              <Button
                type="link"
                size="small"
                icon={<PlayCircleOutlined />}
                onClick={() => handleActivate(record.id)}
              />
            </Tooltip>
          )}
          <Popconfirm
            title="确定要删除此商户吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button
                type="link"
                size="small"
                danger
                icon={<DeleteOutlined />}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const domainColumns = [
    {
      title: '域名',
      dataIndex: 'domain',
      key: 'domain',
      render: (domain: string, record: TenantDomain) => (
        <Space>
          {domain}
          {record.primary && <Tag color="gold">主域名</Tag>}
        </Space>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => (
        <Tag color={type === 'SUBDOMAIN' ? 'blue' : 'green'}>{type}</Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap: Record<string, { color: string; text: string }> = {
          ACTIVE: { color: 'success', text: '活跃' },
          PENDING: { color: 'processing', text: '待验证' },
          VERIFIED: { color: 'success', text: '已验证' },
          ERROR: { color: 'error', text: '错误' },
        };
        const { color, text } = statusMap[status] || { color: 'default', text: status };
        return <Badge status={color as any} text={text} />;
      },
    },
    {
      title: 'SSL',
      dataIndex: 'sslEnabled',
      key: 'sslEnabled',
      render: (enabled: boolean) => (
        <Badge status={enabled ? 'success' : 'default'} text={enabled ? '已启用' : '未启用'} />
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      render: (_: any, record: TenantDomain) => (
        <Space size="small">
          {record.status === 'PENDING' && (
            <Tooltip title="验证">
              <Button
                type="link"
                size="small"
                onClick={() => handleVerifyDomain(record.id)}
              >
                验证
              </Button>
            </Tooltip>
          )}
          {!record.primary && record.status === 'ACTIVE' && (
            <Tooltip title="设为主域名">
              <Button
                type="link"
                size="small"
                onClick={() => handleSetPrimaryDomain(record.id)}
              >
                主域名
              </Button>
            </Tooltip>
          )}
          <Popconfirm
            title="确定要删除此域名吗？"
            onConfirm={() => handleDeleteDomain(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button
                type="link"
                size="small"
                danger
                icon={<DeleteOutlined />}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const userColumns = [
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId',
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (role: string) => {
        const colorMap: Record<string, string> = {
          ADMIN: 'red',
          MANAGER: 'orange',
          OPERATOR: 'blue',
          VIEWER: 'default',
        };
        return <Tag color={colorMap[role]}>{role}</Tag>;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap: Record<string, { color: string; text: string }> = {
          ACTIVE: { color: 'success', text: '活跃' },
          INACTIVE: { color: 'default', text: '未激活' },
          SUSPENDED: { color: 'error', text: '已暂停' },
        };
        const { color, text } = statusMap[status] || { color: 'default', text: status };
        return <Badge status={color as any} text={text} />;
      },
    },
    {
      title: '权限数',
      key: 'permissions',
      render: (_: any, record: TenantUser) => record.permissions.length,
    },
    {
      title: '操作',
      key: 'actions',
      width: 150,
      render: (_: any, record: TenantUser) => (
        <Space size="small">
          <Select
            defaultValue={record.role}
            size="small"
            style={{ width: 100 }}
            onChange={(role) => handleUpdateUserRole(record.userId, role as 'ADMIN' | 'MANAGER' | 'OPERATOR' | 'VIEWER')}
          >
            <Option value="ADMIN">管理员</Option>
            <Option value="MANAGER">经理</Option>
            <Option value="OPERATOR">操作员</Option>
            <Option value="VIEWER">查看者</Option>
          </Select>
          <Popconfirm
            title="确定要移除此用户吗？"
            onConfirm={() => handleRemoveUser(record.userId)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="移除">
              <Button
                type="link"
                size="small"
                danger
                icon={<DeleteOutlined />}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const logColumns = [
    {
      title: '操作时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      render: (date: Date) => new Date(date).toLocaleString('zh-CN'),
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
    },
    {
      title: '操作人',
      dataIndex: 'operator',
      key: 'operator',
    },
    {
      title: '详情',
      dataIndex: 'details',
      key: 'details',
      ellipsis: true,
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {stats && (
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={4}>
            <Card>
              <Statistic
                title="总商户数"
                value={stats.totalTenants}
                prefix={<DashboardOutlined />}
                valueStyle={{ color: '#3f8600' }}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="活跃商户"
                value={stats.activeTenants}
                prefix={<CheckCircleOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="暂停商户"
                value={stats.suspendedTenants}
                prefix={<WarningOutlined />}
                valueStyle={{ color: '#faad14' }}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="试用商户"
                value={stats.trialTenants}
                prefix={<ClockCircleOutlined />}
                valueStyle={{ color: '#722ed1' }}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="总用户数"
                value={stats.totalUsers}
                prefix={<UserOutlined />}
              />
            </Card>
          </Col>
          <Col span={4}>
            <Card>
              <Statistic
                title="总店铺数"
                value={stats.totalShops}
                prefix={<GlobalOutlined />}
              />
            </Card>
          </Col>
        </Row>
      )}

      <Card
        title="SaaS多商户管理"
        extra={
          <Space>
            <Input
              placeholder="搜索商户代码或名称"
              prefix={<SearchOutlined />}
              style={{ width: 200 }}
              value={searchText}
              onChange={e => setSearchText(e.target.value)}
              allowClear
            />
            <Select
              placeholder="状态筛选"
              style={{ width: 120 }}
              allowClear
              value={filters.status || undefined}
              onChange={value => setFilters({ ...filters, status: value as string })}
            >
              <Option value="ACTIVE">活跃</Option>
              <Option value="SUSPENDED">暂停</Option>
              <Option value="CANCELED">已取消</Option>
            </Select>
            <Select
              placeholder="类型筛选"
              style={{ width: 120 }}
              allowClear
              value={filters.type || undefined}
              onChange={value => setFilters({ ...filters, type: value as string })}
            >
              <Option value="SAAS">SaaS</Option>
              <Option value="ENTERPRISE">企业版</Option>
              <Option value="TRIAL">试用版</Option>
            </Select>
            <Select
              placeholder="套餐筛选"
              style={{ width: 120 }}
              allowClear
              value={filters.plan || undefined}
              onChange={value => setFilters({ ...filters, plan: value as string })}
            >
              <Option value="BASIC">基础版</Option>
              <Option value="PRO">专业版</Option>
              <Option value="ENTERPRISE">企业版</Option>
            </Select>
            <Tooltip title="导出数据">
              <Button icon={<ExportOutlined />} onClick={handleExport}>
                导出
              </Button>
            </Tooltip>
            <Button icon={<ReloadOutlined />} onClick={loadTenants}>
              刷新
            </Button>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => setModalVisible(true)}
            >
              创建商户
            </Button>
          </Space>
        }
      >
        {selectedRowKeys.length > 0 && (
          <Alert
            message={`已选择 ${selectedRowKeys.length} 个商户`}
            description={
              <Space>
                <Button size="small" onClick={handleBatchActivate}>
                  批量激活
                </Button>
                <Button size="small" onClick={handleBatchSuspend}>
                  批量暂停
                </Button>
              </Space>
            }
            type="info"
            showIcon
            closable
            onClose={() => setSelectedRowKeys([])}
            style={{ marginBottom: 16 }}
          />
        )}
        
        <Table
          columns={columns}
          dataSource={filteredTenants}
          rowKey="id"
          loading={loading}
          pagination={{ 
            pageSize: 10,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
          rowSelection={{
            selectedRowKeys,
            onChange: setSelectedRowKeys,
          }}
        />
      </Card>

      <Modal
        title="创建新商户"
        open={modalVisible}
        onOk={handleCreate}
        onCancel={() => {
          setModalVisible(false);
          form.resetFields();
        }}
        width={700}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="code"
                label="商户代码"
                rules={[
                  { required: true, message: '请输入商户代码' },
                  { pattern: /^[a-z0-9-]+$/, message: '只能包含小写字母、数字和连字符' },
                ]}
              >
                <Input placeholder="例如: merchant1" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="name"
                label="商户名称"
                rules={[{ required: true, message: '请输入商户名称' }]}
              >
                <Input placeholder="例如: 示例商户" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="type"
                label="商户类型"
                rules={[{ required: true, message: '请选择商户类型' }]}
              >
                <Select placeholder="选择商户类型">
                  <Option value="SAAS">SaaS</Option>
                  <Option value="ENTERPRISE">企业版</Option>
                  <Option value="TRIAL">试用版</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="plan"
                label="套餐"
                rules={[{ required: true, message: '请选择套餐' }]}
              >
                <Select placeholder="选择套餐">
                  <Option value="BASIC">基础版</Option>
                  <Option value="PRO">专业版</Option>
                  <Option value="ENTERPRISE">企业版</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="status"
                label="初始状态"
                rules={[{ required: true, message: '请选择初始状态' }]}
                initialValue="ACTIVE"
              >
                <Select placeholder="选择初始状态">
                  <Option value="ACTIVE">活跃</Option>
                  <Option value="SUSPENDED">暂停</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="maxUsers"
                label="最大用户数"
                rules={[{ required: true, message: '请输入最大用户数' }]}
              >
                <InputNumber min={1} max={1000} style={{ width: '100%' }} placeholder="5" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="maxShops"
                label="最大店铺数"
                rules={[{ required: true, message: '请输入最大店铺数' }]}
              >
                <InputNumber min={1} max={100} style={{ width: '100%' }} placeholder="3" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="storageQuota"
                label="存储配额 (MB)"
                rules={[{ required: true, message: '请输入存储配额' }]}
              >
                <InputNumber min={100} max={100000} style={{ width: '100%' }} placeholder="1024" />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            name="expiresAt"
            label="到期时间"
          >
            <DatePicker style={{ width: '100%' }} placeholder="选择到期时间" />
          </Form.Item>
          <Form.Item
            name="features"
            label="功能模块"
          >
            <Select mode="multiple" placeholder="选择功能模块">
              <Option value="analytics">数据分析</Option>
              <Option value="ai_pricing">AI定价</Option>
              <Option value="auto_publish">自动发布</Option>
              <Option value="inventory_sync">库存同步</Option>
              <Option value="order_sync">订单同步</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="config"
            label="配置 (JSON)"
          >
            <TextArea rows={4} placeholder='{"key": "value"}' />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="编辑商户"
        open={editModalVisible}
        onOk={handleEdit}
        onCancel={() => {
          setEditModalVisible(false);
          editForm.resetFields();
        }}
        width={700}
        destroyOnClose
      >
        <Form form={editForm} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="商户名称"
                rules={[{ required: true, message: '请输入商户名称' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="plan"
                label="套餐"
                rules={[{ required: true, message: '请选择套餐' }]}
              >
                <Select>
                  <Option value="BASIC">基础版</Option>
                  <Option value="PRO">专业版</Option>
                  <Option value="ENTERPRISE">企业版</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="maxUsers"
                label="最大用户数"
                rules={[{ required: true, message: '请输入最大用户数' }]}
              >
                <InputNumber min={1} max={1000} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="maxShops"
                label="最大店铺数"
                rules={[{ required: true, message: '请输入最大店铺数' }]}
              >
                <InputNumber min={1} max={100} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="storageQuota"
                label="存储配额 (MB)"
                rules={[{ required: true, message: '请输入存储配额' }]}
              >
                <InputNumber min={100} max={100000} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            name="expiresAt"
            label="到期时间"
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={`商户管理 - ${selectedTenant?.name}`}
        open={!!selectedTenant}
        onCancel={() => setSelectedTenant(null)}
        footer={null}
        width={1200}
        destroyOnClose
      >
        {selectedTenant && (
          <Tabs defaultActiveKey="overview">
            <TabPane tab={<span><DashboardOutlined /> 概览</span>} key="overview">
              <Row gutter={16} style={{ marginBottom: 16 }}>
                <Col span={6}>
                  <Card size="small">
                    <Statistic
                      title="用户数"
                      value={users.length}
                      prefix={<UserOutlined />}
                    />
                  </Card>
                </Col>
                <Col span={6}>
                  <Card size="small">
                    <Statistic
                      title="域名数"
                      value={domains.length}
                      prefix={<GlobalOutlined />}
                    />
                  </Card>
                </Col>
                <Col span={6}>
                  <Card size="small">
                    <Statistic
                      title="存储使用"
                      value={usage?.storageUsed || 0}
                      suffix={`/ ${selectedTenant.storageQuota} MB`}
                      prefix={<BarChartOutlined />}
                    />
                  </Card>
                </Col>
                <Col span={6}>
                  <Card size="small">
                    <Statistic
                      title="API调用"
                      value={usage?.apiCalls || 0}
                      prefix={<BellOutlined />}
                    />
                  </Card>
                </Col>
              </Row>
              
              {usage && (
                <Card size="small" title="配额使用情况" style={{ marginBottom: 16 }}>
                  <Row gutter={16}>
                    <Col span={12}>
                      <div style={{ marginBottom: 8 }}>
                        <Text>存储使用率</Text>
                        <Progress 
                          percent={Math.round((usage.storageUsed / selectedTenant.storageQuota) * 100)} 
                          status={usage.storageUsed / selectedTenant.storageQuota > 0.9 ? 'exception' : 'normal'}
                        />
                      </div>
                    </Col>
                    <Col span={12}>
                      <div style={{ marginBottom: 8 }}>
                        <Text>用户使用率</Text>
                        <Progress 
                          percent={Math.round((users.length / selectedTenant.maxUsers) * 100)} 
                          status={users.length / selectedTenant.maxUsers > 0.9 ? 'exception' : 'normal'}
                        />
                      </div>
                    </Col>
                  </Row>
                </Card>
              )}

              <Descriptions bordered column={2} size="small">
                <Descriptions.Item label="商户代码">{selectedTenant.code}</Descriptions.Item>
                <Descriptions.Item label="商户名称">{selectedTenant.name}</Descriptions.Item>
                <Descriptions.Item label="类型">
                  <Tag color={selectedTenant.type === 'SAAS' ? 'green' : selectedTenant.type === 'ENTERPRISE' ? 'purple' : 'orange'}>
                    {selectedTenant.type}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="套餐">
                  <Tag color={selectedTenant.plan === 'BASIC' ? 'default' : selectedTenant.plan === 'PRO' ? 'blue' : 'gold'}>
                    {selectedTenant.plan}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="状态">
                  <Badge 
                    status={selectedTenant.status === 'ACTIVE' ? 'success' : 'warning'} 
                    text={selectedTenant.status === 'ACTIVE' ? '活跃' : '暂停'} 
                  />
                </Descriptions.Item>
                <Descriptions.Item label="创建时间">
                  {new Date(selectedTenant.createdAt).toLocaleString('zh-CN')}
                </Descriptions.Item>
                <Descriptions.Item label="最大用户数">{selectedTenant.maxUsers}</Descriptions.Item>
                <Descriptions.Item label="最大店铺数">{selectedTenant.maxShops}</Descriptions.Item>
                <Descriptions.Item label="存储配额">{selectedTenant.storageQuota} MB</Descriptions.Item>
                <Descriptions.Item label="到期时间">
                  {selectedTenant.expiresAt ? new Date(selectedTenant.expiresAt).toLocaleString('zh-CN') : '永久'}
                </Descriptions.Item>
                <Descriptions.Item label="功能模块" span={2}>
                  <Space wrap>
                    {selectedTenant.features.length > 0 ? 
                      selectedTenant.features.map(f => <Tag key={f}>{f}</Tag>) : 
                      <Tag>无</Tag>
                    }
                  </Space>
                </Descriptions.Item>
              </Descriptions>
            </TabPane>

            <TabPane tab={<span><GlobalOutlined /> 域名管理</span>} key="domains">
              <Space direction="vertical" style={{ width: '100%' }}>
                <Card size="small">
                  <Form form={domainForm} layout="inline">
                    <Form.Item
                      name="domain"
                      rules={[{ required: true, message: '请输入域名' }]}
                    >
                      <Input placeholder="域名" />
                    </Form.Item>
                    <Form.Item
                      name="type"
                      initialValue="SUBDOMAIN"
                      rules={[{ required: true, message: '请选择域名类型' }]}
                    >
                      <Select style={{ width: 150 }}>
                        <Option value="SUBDOMAIN">子域名</Option>
                        <Option value="CUSTOM_DOMAIN">自定义域名</Option>
                      </Select>
                    </Form.Item>
                    <Form.Item>
                      <Button type="primary" onClick={handleAddDomain}>
                        添加域名
                      </Button>
                    </Form.Item>
                  </Form>
                </Card>
                <Table
                  columns={domainColumns}
                  dataSource={domains}
                  rowKey="id"
                  pagination={false}
                  size="small"
                />
              </Space>
            </TabPane>

            <TabPane tab={<span><UserOutlined /> 用户管理</span>} key="users">
              <Space direction="vertical" style={{ width: '100%' }}>
                <Card size="small">
                  <Form form={userForm} layout="inline">
                    <Form.Item
                      name="userId"
                      rules={[{ required: true, message: '请输入用户ID' }]}
                    >
                      <Input placeholder="用户ID" />
                    </Form.Item>
                    <Form.Item
                      name="role"
                      initialValue="OPERATOR"
                      rules={[{ required: true, message: '请选择角色' }]}
                    >
                      <Select style={{ width: 150 }}>
                        <Option value="ADMIN">管理员</Option>
                        <Option value="MANAGER">经理</Option>
                        <Option value="OPERATOR">操作员</Option>
                        <Option value="VIEWER">查看者</Option>
                      </Select>
                    </Form.Item>
                    <Form.Item>
                      <Button type="primary" onClick={handleAddUser}>
                        添加用户
                      </Button>
                    </Form.Item>
                  </Form>
                </Card>
                <Table
                  columns={userColumns}
                  dataSource={users}
                  rowKey="id"
                  pagination={false}
                  size="small"
                />
              </Space>
            </TabPane>

            <TabPane tab={<span><SettingOutlined /> 设置</span>} key="settings">
              <Card>
                <Descriptions bordered column={1} size="small">
                  {Object.entries(settings).map(([key, value]) => (
                    <Descriptions.Item key={key} label={key}>
                      {value}
                    </Descriptions.Item>
                  ))}
                  {Object.keys(settings).length === 0 && (
                    <Descriptions.Item label="提示">
                      暂无设置项
                    </Descriptions.Item>
                  )}
                </Descriptions>
              </Card>
            </TabPane>

            <TabPane tab={<span><FileTextOutlined /> 操作日志</span>} key="logs">
              <Table
                columns={logColumns}
                dataSource={logs}
                rowKey="id"
                pagination={{ pageSize: 10 }}
                size="small"
              />
            </TabPane>
          </Tabs>
        )}
      </Modal>
    </div>
  );
}