import React, { useState, useEffect, useCallback } from 'react';
import {
  Card,
  Typography,
  Row,
  Col,
  Button,
  Table,
  Tag,
  Space,
  Modal,
  Form,
  Input,
  Select,
  Upload,
  message,
  Tabs,
  Badge,
  Drawer,
  Descriptions,
  Timeline,
  Alert,
  Progress,
  Statistic,
  DatePicker,
  Tooltip,
  Popconfirm,
} from 'antd';
import {
  AuditOutlined,
  PlusOutlined,
  UploadOutlined,
  EyeOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  WarningOutlined,
  FileTextOutlined,
  SafetyOutlined,
  SearchOutlined,
  FilterOutlined,
  ReloadOutlined,
  CheckOutlined,
  DeleteOutlined,
  DownloadOutlined,
  HistoryOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import moment from 'moment';

const { Title, Text } = Typography;
const { Option } = Select;
const { TabPane } = Tabs;
const { Search } = Input;
const { RangePicker } = DatePicker;
const { Dragger } = Upload;

// 证书类型
interface Certificate {
  id: string;
  name: string;
  type: 'PRODUCT_CERT' | 'BUSINESS_LICENSE' | 'QUALITY_CERT' | 'SAFETY_CERT' | 'OTHER';
  status: 'PENDING' | 'APPROVED' | 'REJECTED' | 'EXPIRED';
  fileUrl: string;
  fileName: string;
  uploadDate: string;
  expiryDate: string;
  approvedBy?: string;
  approvedDate?: string;
  rejectReason?: string;
  productId?: string;
  productName?: string;
  notes?: string;
}

// 合规检查记录
interface ComplianceCheck {
  id: string;
  productId: string;
  productName: string;
  checkType: 'CERTIFICATE' | 'PLATFORM_RULE' | 'SAFETY' | 'QUALITY';
  status: 'PASS' | 'FAIL' | 'WARNING';
  checkedAt: string;
  checkedBy: string;
  issues: ComplianceIssue[];
  suggestions: string[];
}

interface ComplianceIssue {
  type: 'ERROR' | 'WARNING' | 'INFO';
  message: string;
  field?: string;
}

// 风险监控记录
interface RiskMonitor {
  id: string;
  type: 'CERTIFICATE_EXPIRY' | 'COMPLIANCE_VIOLATION' | 'PLATFORM_PENALTY';
  level: 'HIGH' | 'MEDIUM' | 'LOW';
  title: string;
  description: string;
  createdAt: string;
  status: 'OPEN' | 'RESOLVED' | 'IGNORED';
  relatedId?: string;
}

const CERT_TYPE_MAP: Record<string, { color: string; text: string }> = {
  PRODUCT_CERT: { color: 'blue', text: '产品认证' },
  BUSINESS_LICENSE: { color: 'green', text: '营业执照' },
  QUALITY_CERT: { color: 'purple', text: '质量认证' },
  SAFETY_CERT: { color: 'orange', text: '安全认证' },
  OTHER: { color: 'default', text: '其他' },
};

const CERT_STATUS_MAP: Record<string, { color: string; text: string; icon: React.ReactNode }> = {
  PENDING: { color: 'warning', text: '待审核', icon: <ClockCircleOutlined /> },
  APPROVED: { color: 'success', text: '已通过', icon: <CheckCircleOutlined /> },
  REJECTED: { color: 'error', text: '已拒绝', icon: <CloseCircleOutlined /> },
  EXPIRED: { color: 'default', text: '已过期', icon: <WarningOutlined /> },
};

const CHECK_STATUS_MAP: Record<string, { color: string; text: string; icon: React.ReactNode }> = {
  PASS: { color: 'success', text: '通过', icon: <CheckCircleOutlined /> },
  FAIL: { color: 'error', text: '失败', icon: <CloseCircleOutlined /> },
  WARNING: { color: 'warning', text: '警告', icon: <WarningOutlined /> },
};

const RISK_LEVEL_MAP: Record<string, { color: string; text: string }> = {
  HIGH: { color: 'red', text: '高风险' },
  MEDIUM: { color: 'orange', text: '中风险' },
  LOW: { color: 'blue', text: '低风险' },
};

// Mock Data
const MOCK_CERTIFICATES: Certificate[] = [
  {
    id: '1',
    name: 'CE认证证书',
    type: 'PRODUCT_CERT',
    status: 'APPROVED',
    fileUrl: '/files/ce-cert.pdf',
    fileName: 'CE-Certificate-2026.pdf',
    uploadDate: '2026-03-15',
    expiryDate: '2027-03-15',
    approvedBy: 'admin',
    approvedDate: '2026-03-16',
    productId: 'P001',
    productName: '工业温度传感器',
    notes: '欧盟市场准入认证',
  },
  {
    id: '2',
    name: '营业执照',
    type: 'BUSINESS_LICENSE',
    status: 'APPROVED',
    fileUrl: '/files/business-license.pdf',
    fileName: 'Business-License-2026.pdf',
    uploadDate: '2026-01-10',
    expiryDate: '2027-01-10',
    approvedBy: 'admin',
    approvedDate: '2026-01-11',
    notes: '企业营业执照',
  },
  {
    id: '3',
    name: 'FCC认证',
    type: 'SAFETY_CERT',
    status: 'PENDING',
    fileUrl: '/files/fcc-cert.pdf',
    fileName: 'FCC-Certificate.pdf',
    uploadDate: '2026-03-18',
    expiryDate: '2027-03-18',
    productId: 'P002',
    productName: 'PLC控制器',
    notes: '美国FCC认证',
  },
  {
    id: '4',
    name: 'ISO9001',
    type: 'QUALITY_CERT',
    status: 'EXPIRED',
    fileUrl: '/files/iso9001.pdf',
    fileName: 'ISO9001-2025.pdf',
    uploadDate: '2025-01-01',
    expiryDate: '2026-01-01',
    approvedBy: 'admin',
    approvedDate: '2025-01-02',
    notes: '质量管理体系认证，已过期需要更新',
  },
];

const MOCK_COMPLIANCE_CHECKS: ComplianceCheck[] = [
  {
    id: '1',
    productId: 'P001',
    productName: '工业温度传感器',
    checkType: 'CERTIFICATE',
    status: 'PASS',
    checkedAt: '2026-03-18 10:00:00',
    checkedBy: 'system',
    issues: [],
    suggestions: ['建议定期更新CE认证'],
  },
  {
    id: '2',
    productId: 'P002',
    productName: 'PLC控制器',
    checkType: 'PLATFORM_RULE',
    status: 'WARNING',
    checkedAt: '2026-03-18 09:30:00',
    checkedBy: 'system',
    issues: [
      { type: 'WARNING', message: '产品描述缺少安全警告', field: 'description' },
    ],
    suggestions: ['添加必要的安全使用警告'],
  },
  {
    id: '3',
    productId: 'P003',
    productName: '压力传感器',
    checkType: 'SAFETY',
    status: 'FAIL',
    checkedAt: '2026-03-18 08:00:00',
    checkedBy: 'admin',
    issues: [
      { type: 'ERROR', message: '缺少防爆认证', field: 'certificates' },
      { type: 'WARNING', message: '工作压力范围未标注清楚', field: 'specifications' },
    ],
    suggestions: ['申请防爆认证', '完善产品规格说明'],
  },
];

const MOCK_RISKS: RiskMonitor[] = [
  {
    id: '1',
    type: 'CERTIFICATE_EXPIRY',
    level: 'HIGH',
    title: 'ISO9001认证即将过期',
    description: 'ISO9001质量管理体系认证将于30天后过期，请及时更新',
    createdAt: '2026-03-18 10:00:00',
    status: 'OPEN',
    relatedId: '4',
  },
  {
    id: '2',
    type: 'COMPLIANCE_VIOLATION',
    level: 'MEDIUM',
    title: '压力传感器缺少防爆认证',
    description: '产品P003在合规检查中发现缺少必要的防爆认证',
    createdAt: '2026-03-18 08:00:00',
    status: 'OPEN',
    relatedId: '3',
  },
  {
    id: '3',
    type: 'PLATFORM_PENALTY',
    level: 'LOW',
    title: 'Amazon平台警告',
    description: '收到Amazon平台关于产品描述的警告',
    createdAt: '2026-03-17 15:00:00',
    status: 'RESOLVED',
  },
];

const ComplianceManagement: React.FC = () => {
  const [activeTab, setActiveTab] = useState('certificates');
  const [certificates, setCertificates] = useState<Certificate[]>([]);
  const [complianceChecks, setComplianceChecks] = useState<ComplianceCheck[]>([]);
  const [risks, setRisks] = useState<RiskMonitor[]>([]);
  const [loading, setLoading] = useState(false);

  // 证书相关状态
  const [uploadModalVisible, setUploadModalVisible] = useState(false);
  const [auditModalVisible, setAuditModalVisible] = useState(false);
  const [detailDrawerVisible, setDetailDrawerVisible] = useState(false);
  const [currentCertificate, setCurrentCertificate] = useState<Certificate | null>(null);
  const [uploadForm] = Form.useForm();
  const [auditForm] = Form.useForm();
  const [certFilters, setCertFilters] = useState({
    keyword: '',
    type: '',
    status: '',
  });

  // 合规检查相关状态
  const [checkModalVisible, setCheckModalVisible] = useState(false);
  const [checkForm] = Form.useForm();
  const [checkFilters, setCheckFilters] = useState({
    keyword: '',
    type: '',
    status: '',
  });

  // 风险监控相关状态
  const [riskFilters, setRiskFilters] = useState({
    keyword: '',
    level: '',
    status: '',
  });

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = useCallback(async () => {
    setLoading(true);
    await new Promise(resolve => setTimeout(resolve, 500));
    setCertificates(MOCK_CERTIFICATES);
    setComplianceChecks(MOCK_COMPLIANCE_CHECKS);
    setRisks(MOCK_RISKS);
    setLoading(false);
  }, []);

  // ==================== 证书管理功能 ====================

  const handleUploadCertificate = () => {
    uploadForm.resetFields();
    setUploadModalVisible(true);
  };

  const handleUploadSubmit = async () => {
    try {
      const values = await uploadForm.validateFields();
      const newCert: Certificate = {
        id: `${Date.now()}`,
        name: values.name,
        type: values.type,
        status: 'PENDING',
        fileUrl: '/files/uploaded.pdf',
        fileName: values.file?.file?.name || 'uploaded.pdf',
        uploadDate: moment().format('YYYY-MM-DD'),
        expiryDate: values.expiryDate.format('YYYY-MM-DD'),
        productId: values.productId,
        productName: values.productName,
        notes: values.notes,
      };
      setCertificates([newCert, ...certificates]);
      setUploadModalVisible(false);
      message.success('证书上传成功，等待审核');
    } catch (error) {
      console.error('Upload failed:', error);
    }
  };

  const handleAuditCertificate = (record: Certificate) => {
    setCurrentCertificate(record);
    auditForm.resetFields();
    setAuditModalVisible(true);
  };

  const handleAuditSubmit = async () => {
    try {
      const values = await auditForm.validateFields();
      if (currentCertificate) {
        const updatedCerts = certificates.map(cert =>
          cert.id === currentCertificate.id
            ? {
                ...cert,
                status: values.status,
                approvedBy: values.status === 'APPROVED' ? 'admin' : undefined,
                approvedDate: values.status === 'APPROVED' ? moment().format('YYYY-MM-DD') : undefined,
                rejectReason: values.status === 'REJECTED' ? values.rejectReason : undefined,
              }
            : cert
        );
        setCertificates(updatedCerts);
        setAuditModalVisible(false);
        message.success(`证书已${values.status === 'APPROVED' ? '通过' : '拒绝'}`);
      }
    } catch (error) {
      console.error('Audit failed:', error);
    }
  };

  const handleViewCertificate = (record: Certificate) => {
    setCurrentCertificate(record);
    setDetailDrawerVisible(true);
  };

  const handleDeleteCertificate = (id: string) => {
    setCertificates(certificates.filter(cert => cert.id !== id));
    message.success('证书已删除');
  };

  const handleDownloadCertificate = (record: Certificate) => {
    message.success(`开始下载: ${record.fileName}`);
  };

  // ==================== 合规检查功能 ====================

  const handleRunComplianceCheck = () => {
    checkForm.resetFields();
    setCheckModalVisible(true);
  };

  const handleCheckSubmit = async () => {
    try {
      const values = await checkForm.validateFields();
      message.loading('正在执行合规检查...', 1.5);
      
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      const newCheck: ComplianceCheck = {
        id: `${Date.now()}`,
        productId: values.productId,
        productName: '选中产品',
        checkType: values.checkType,
        status: Math.random() > 0.5 ? 'PASS' : Math.random() > 0.5 ? 'WARNING' : 'FAIL',
        checkedAt: moment().format('YYYY-MM-DD HH:mm:ss'),
        checkedBy: 'admin',
        issues: [],
        suggestions: ['建议定期复查'],
      };
      
      setComplianceChecks([newCheck, ...complianceChecks]);
      setCheckModalVisible(false);
      message.success('合规检查完成');
    } catch (error) {
      console.error('Check failed:', error);
    }
  };

  // ==================== 风险监控功能 ====================

  const handleResolveRisk = (id: string) => {
    setRisks(risks.map(risk => 
      risk.id === id ? { ...risk, status: 'RESOLVED' as const } : risk
    ));
    message.success('风险已标记为已解决');
  };

  const handleIgnoreRisk = (id: string) => {
    setRisks(risks.map(risk => 
      risk.id === id ? { ...risk, status: 'IGNORED' as const } : risk
    ));
    message.success('风险已忽略');
  };

  // ==================== 表格列定义 ====================

  const certColumns: ColumnsType<Certificate> = [
    {
      title: '证书名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space direction="vertical" size={0}>
          <Text strong>{text}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>{record.fileName}</Text>
        </Space>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type) => <Tag color={CERT_TYPE_MAP[type].color}>{CERT_TYPE_MAP[type].text}</Tag>,
    },
    {
      title: '关联产品',
      dataIndex: 'productName',
      key: 'productName',
      render: (text) => text || '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const config = CERT_STATUS_MAP[status];
        return <Tag color={config.color} icon={config.icon}>{config.text}</Tag>;
      },
    },
    {
      title: '有效期至',
      dataIndex: 'expiryDate',
      key: 'expiryDate',
      render: (date) => {
        const days = moment(date).diff(moment(), 'days');
        const isExpiringSoon = days <= 30 && days > 0;
        const isExpired = days <= 0;
        return (
          <Space direction="vertical" size={0}>
            <Text>{date}</Text>
            {isExpiringSoon && <Text type="warning" style={{ fontSize: 12 }}>即将过期 ({days}天)</Text>}
            {isExpired && <Text type="danger" style={{ fontSize: 12 }}>已过期</Text>}
          </Space>
        );
      },
    },
    {
      title: '上传日期',
      dataIndex: 'uploadDate',
      key: 'uploadDate',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="small">
          <Button type="link" size="small" icon={<EyeOutlined />} onClick={() => handleViewCertificate(record)}>
            查看
          </Button>
          <Button type="link" size="small" icon={<DownloadOutlined />} onClick={() => handleDownloadCertificate(record)}>
            下载
          </Button>
          {record.status === 'PENDING' && (
            <Button type="link" size="small" icon={<CheckOutlined />} onClick={() => handleAuditCertificate(record)}>
              审核
            </Button>
          )}
          <Popconfirm
            title="确认删除"
            description="确定要删除此证书吗？"
            onConfirm={() => handleDeleteCertificate(record.id)}
            okText="删除"
            cancelText="取消"
          >
            <Button type="link" size="small" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const checkColumns: ColumnsType<ComplianceCheck> = [
    {
      title: '产品',
      dataIndex: 'productName',
      key: 'productName',
      render: (text, record) => (
        <Space direction="vertical" size={0}>
          <Text strong>{text}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>{record.productId}</Text>
        </Space>
      ),
    },
    {
      title: '检查类型',
      dataIndex: 'checkType',
      key: 'checkType',
      render: (type) => {
        const typeMap: Record<string, string> = {
          CERTIFICATE: '证书检查',
          PLATFORM_RULE: '平台规则',
          SAFETY: '安全检查',
          QUALITY: '质量检查',
        };
        return <Tag>{typeMap[type]}</Tag>;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const config = CHECK_STATUS_MAP[status];
        return <Tag color={config.color} icon={config.icon}>{config.text}</Tag>;
      },
    },
    {
      title: '问题数',
      key: 'issues',
      render: (_, record) => (
        <Badge 
          count={record.issues.length} 
          style={{ backgroundColor: record.issues.length > 0 ? '#ff4d4f' : '#52c41a' }}
        />
      ),
    },
    {
      title: '检查时间',
      dataIndex: 'checkedAt',
      key: 'checkedAt',
    },
    {
      title: '检查人',
      dataIndex: 'checkedBy',
      key: 'checkedBy',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button type="link" size="small" icon={<EyeOutlined />} onClick={() => {}}>
          详情
        </Button>
      ),
    },
  ];

  const riskColumns: ColumnsType<RiskMonitor> = [
    {
      title: '风险标题',
      dataIndex: 'title',
      key: 'title',
      render: (text, record) => (
        <Space direction="vertical" size={0}>
          <Text strong>{text}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>{record.description}</Text>
        </Space>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type) => {
        const typeMap: Record<string, string> = {
          CERTIFICATE_EXPIRY: '证书过期',
          COMPLIANCE_VIOLATION: '合规违规',
          PLATFORM_PENALTY: '平台处罚',
        };
        return <Tag>{typeMap[type]}</Tag>;
      },
    },
    {
      title: '风险等级',
      dataIndex: 'level',
      key: 'level',
      render: (level) => <Tag color={RISK_LEVEL_MAP[level].color}>{RISK_LEVEL_MAP[level].text}</Tag>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const statusMap: Record<string, { color: string; text: string }> = {
          OPEN: { color: 'error', text: '待处理' },
          RESOLVED: { color: 'success', text: '已解决' },
          IGNORED: { color: 'default', text: '已忽略' },
        };
        return <Tag color={statusMap[status].color}>{statusMap[status].text}</Tag>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="small">
          {record.status === 'OPEN' && (
            <>
              <Button type="link" size="small" icon={<CheckOutlined />} onClick={() => handleResolveRisk(record.id)}>
                解决
              </Button>
              <Button type="link" size="small" onClick={() => handleIgnoreRisk(record.id)}>
                忽略
              </Button>
            </>
          )}
        </Space>
      ),
    },
  ];

  // ==================== 统计数据 ====================

  const certStats = {
    total: certificates.length,
    pending: certificates.filter(c => c.status === 'PENDING').length,
    approved: certificates.filter(c => c.status === 'APPROVED').length,
    expired: certificates.filter(c => c.status === 'EXPIRED').length,
    expiringSoon: certificates.filter(c => {
      const days = moment(c.expiryDate).diff(moment(), 'days');
      return days <= 30 && days > 0;
    }).length,
  };

  const riskStats = {
    total: risks.length,
    high: risks.filter(r => r.level === 'HIGH' && r.status === 'OPEN').length,
    medium: risks.filter(r => r.level === 'MEDIUM' && r.status === 'OPEN').length,
    low: risks.filter(r => r.level === 'LOW' && r.status === 'OPEN').length,
  };

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <Title level={4}>合规管理</Title>
        <Space>
          <Button icon={<ReloadOutlined />} onClick={fetchData}>
            刷新
          </Button>
        </Space>
      </div>

      <Tabs activeKey={activeTab} onChange={setActiveTab} style={{ marginBottom: 24 }}>
        <TabPane
          tab={
            <span>
              <FileTextOutlined />
              证书管理
              <Badge count={certStats.pending} style={{ marginLeft: 8 }} />
            </span>
          }
          key="certificates"
        >
          <Row gutter={16} style={{ marginBottom: 16 }}>
            <Col span={4}>
              <Card size="small">
                <Statistic title="总证书数" value={certStats.total} />
              </Card>
            </Col>
            <Col span={4}>
              <Card size="small">
                <Statistic title="待审核" value={certStats.pending} valueStyle={{ color: '#faad14' }} />
              </Card>
            </Col>
            <Col span={4}>
              <Card size="small">
                <Statistic title="已通过" value={certStats.approved} valueStyle={{ color: '#52c41a' }} />
              </Card>
            </Col>
            <Col span={4}>
              <Card size="small">
                <Statistic title="已过期" value={certStats.expired} valueStyle={{ color: '#ff4d4f' }} />
              </Card>
            </Col>
            <Col span={4}>
              <Card size="small">
                <Statistic title="即将过期" value={certStats.expiringSoon} valueStyle={{ color: '#faad14' }} />
              </Card>
            </Col>
            <Col span={4}>
              <Button type="primary" icon={<UploadOutlined />} onClick={handleUploadCertificate} block>
                上传证书
              </Button>
            </Col>
          </Row>

          <Card>
            <Row gutter={16} style={{ marginBottom: 16 }}>
              <Col span={8}>
                <Search
                  placeholder="搜索证书名称"
                  allowClear
                  onSearch={(value) => setCertFilters({ ...certFilters, keyword: value })}
                />
              </Col>
              <Col span={4}>
                <Select
                  placeholder="证书类型"
                  allowClear
                  style={{ width: '100%' }}
                  onChange={(value) => setCertFilters({ ...certFilters, type: value })}
                >
                  {Object.entries(CERT_TYPE_MAP).map(([key, config]) => (
                    <Option key={key} value={key}>{config.text}</Option>
                  ))}
                </Select>
              </Col>
              <Col span={4}>
                <Select
                  placeholder="状态"
                  allowClear
                  style={{ width: '100%' }}
                  onChange={(value) => setCertFilters({ ...certFilters, status: value })}
                >
                  {Object.entries(CERT_STATUS_MAP).map(([key, config]) => (
                    <Option key={key} value={key}>{config.text}</Option>
                  ))}
                </Select>
              </Col>
            </Row>

            <Table
              columns={certColumns}
              dataSource={certificates.filter(cert => {
                if (certFilters.keyword && !cert.name.toLowerCase().includes(certFilters.keyword.toLowerCase())) return false;
                if (certFilters.type && cert.type !== certFilters.type) return false;
                if (certFilters.status && cert.status !== certFilters.status) return false;
                return true;
              })}
              rowKey="id"
              loading={loading}
              pagination={{ pageSize: 10 }}
            />
          </Card>
        </TabPane>

        <TabPane
          tab={
            <span>
              <AuditOutlined />
              合规检查
            </span>
          }
          key="compliance"
        >
          <Row gutter={16} style={{ marginBottom: 16 }}>
            <Col span={6}>
              <Card size="small">
                <Statistic
                  title="通过"
                  value={complianceChecks.filter(c => c.status === 'PASS').length}
                  valueStyle={{ color: '#52c41a' }}
                  prefix={<CheckCircleOutlined />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card size="small">
                <Statistic
                  title="警告"
                  value={complianceChecks.filter(c => c.status === 'WARNING').length}
                  valueStyle={{ color: '#faad14' }}
                  prefix={<WarningOutlined />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card size="small">
                <Statistic
                  title="失败"
                  value={complianceChecks.filter(c => c.status === 'FAIL').length}
                  valueStyle={{ color: '#ff4d4f' }}
                  prefix={<CloseCircleOutlined />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Button type="primary" icon={<AuditOutlined />} onClick={handleRunComplianceCheck} block>
                执行检查
              </Button>
            </Col>
          </Row>

          <Card>
            <Table
              columns={checkColumns}
              dataSource={complianceChecks}
              rowKey="id"
              loading={loading}
              pagination={{ pageSize: 10 }}
            />
          </Card>
        </TabPane>

        <TabPane
          tab={
            <span>
              <SafetyOutlined />
              风险监控
              {riskStats.high > 0 && <Badge count={riskStats.high} style={{ marginLeft: 8, backgroundColor: '#ff4d4f' }} />}
            </span>
          }
          key="risks"
        >
          <Row gutter={16} style={{ marginBottom: 16 }}>
            <Col span={6}>
              <Card size="small">
                <Statistic title="总风险数" value={riskStats.total} />
              </Card>
            </Col>
            <Col span={6}>
              <Card size="small">
                <Statistic title="高风险" value={riskStats.high} valueStyle={{ color: '#ff4d4f' }} />
              </Card>
            </Col>
            <Col span={6}>
              <Card size="small">
                <Statistic title="中风险" value={riskStats.medium} valueStyle={{ color: '#faad14' }} />
              </Card>
            </Col>
            <Col span={6}>
              <Card size="small">
                <Statistic title="低风险" value={riskStats.low} valueStyle={{ color: '#1890ff' }} />
              </Card>
            </Col>
          </Row>

          <Card>
            <Table
              columns={riskColumns}
              dataSource={risks}
              rowKey="id"
              loading={loading}
              pagination={{ pageSize: 10 }}
            />
          </Card>
        </TabPane>
      </Tabs>

      {/* 上传证书模态框 */}
      <Modal
        title="上传证书"
        open={uploadModalVisible}
        onOk={handleUploadSubmit}
        onCancel={() => setUploadModalVisible(false)}
        width={600}
      >
        <Form form={uploadForm} layout="vertical">
          <Form.Item
            name="name"
            label="证书名称"
            rules={[{ required: true, message: '请输入证书名称' }]}
          >
            <Input placeholder="例如：CE认证证书" />
          </Form.Item>
          <Form.Item
            name="type"
            label="证书类型"
            rules={[{ required: true, message: '请选择证书类型' }]}
          >
            <Select placeholder="选择证书类型">
              {Object.entries(CERT_TYPE_MAP).map(([key, config]) => (
                <Option key={key} value={key}>{config.text}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="productId"
            label="关联产品ID"
          >
            <Input placeholder="输入产品ID（可选）" />
          </Form.Item>
          <Form.Item
            name="productName"
            label="关联产品名称"
          >
            <Input placeholder="输入产品名称（可选）" />
          </Form.Item>
          <Form.Item
            name="expiryDate"
            label="有效期至"
            rules={[{ required: true, message: '请选择有效期' }]}
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="file"
            label="证书文件"
            rules={[{ required: true, message: '请上传证书文件' }]}
          >
            <Dragger
              name="file"
              multiple={false}
              beforeUpload={() => false}
            >
              <p className="ant-upload-drag-icon">
                <UploadOutlined />
              </p>
              <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
              <p className="ant-upload-hint">支持 PDF、JPG、PNG 格式</p>
            </Dragger>
          </Form.Item>
          <Form.Item name="notes" label="备注">
            <Input.TextArea rows={3} placeholder="输入备注信息" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 审核证书模态框 */}
      <Modal
        title="审核证书"
        open={auditModalVisible}
        onOk={handleAuditSubmit}
        onCancel={() => setAuditModalVisible(false)}
      >
        <Form form={auditForm} layout="vertical">
          <Form.Item
            name="status"
            label="审核结果"
            rules={[{ required: true, message: '请选择审核结果' }]}
          >
            <Select placeholder="选择审核结果">
              <Option value="APPROVED">通过</Option>
              <Option value="REJECTED">拒绝</Option>
            </Select>
          </Form.Item>
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.status !== currentValues.status}
          >
            {({ getFieldValue }) =>
              getFieldValue('status') === 'REJECTED' ? (
                <Form.Item
                  name="rejectReason"
                  label="拒绝原因"
                  rules={[{ required: true, message: '请输入拒绝原因' }]}
                >
                  <Input.TextArea rows={3} placeholder="输入拒绝原因" />
                </Form.Item>
              ) : null
            }
          </Form.Item>
        </Form>
      </Modal>

      {/* 证书详情抽屉 */}
      <Drawer
        title="证书详情"
        placement="right"
        onClose={() => setDetailDrawerVisible(false)}
        open={detailDrawerVisible}
        width={500}
      >
        {currentCertificate && (
          <Descriptions column={1} bordered>
            <Descriptions.Item label="证书名称">{currentCertificate.name}</Descriptions.Item>
            <Descriptions.Item label="证书类型">
              <Tag color={CERT_TYPE_MAP[currentCertificate.type].color}>
                {CERT_TYPE_MAP[currentCertificate.type].text}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={CERT_STATUS_MAP[currentCertificate.status].color}>
                {CERT_STATUS_MAP[currentCertificate.status].text}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="文件名">{currentCertificate.fileName}</Descriptions.Item>
            <Descriptions.Item label="关联产品">{currentCertificate.productName || '-'}</Descriptions.Item>
            <Descriptions.Item label="上传日期">{currentCertificate.uploadDate}</Descriptions.Item>
            <Descriptions.Item label="有效期至">{currentCertificate.expiryDate}</Descriptions.Item>
            {currentCertificate.approvedBy && (
              <Descriptions.Item label="审核人">{currentCertificate.approvedBy}</Descriptions.Item>
            )}
            {currentCertificate.approvedDate && (
              <Descriptions.Item label="审核日期">{currentCertificate.approvedDate}</Descriptions.Item>
            )}
            {currentCertificate.rejectReason && (
              <Descriptions.Item label="拒绝原因">{currentCertificate.rejectReason}</Descriptions.Item>
            )}
            {currentCertificate.notes && (
              <Descriptions.Item label="备注">{currentCertificate.notes}</Descriptions.Item>
            )}
          </Descriptions>
        )}
      </Drawer>

      {/* 执行合规检查模态框 */}
      <Modal
        title="执行合规检查"
        open={checkModalVisible}
        onOk={handleCheckSubmit}
        onCancel={() => setCheckModalVisible(false)}
      >
        <Form form={checkForm} layout="vertical">
          <Form.Item
            name="productId"
            label="产品ID"
            rules={[{ required: true, message: '请输入产品ID' }]}
          >
            <Input placeholder="输入要检查的产品ID" />
          </Form.Item>
          <Form.Item
            name="checkType"
            label="检查类型"
            rules={[{ required: true, message: '请选择检查类型' }]}
          >
            <Select placeholder="选择检查类型">
              <Option value="CERTIFICATE">证书检查</Option>
              <Option value="PLATFORM_RULE">平台规则</Option>
              <Option value="SAFETY">安全检查</Option>
              <Option value="QUALITY">质量检查</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ComplianceManagement;
