import React, {useState, useEffect} from 'react';
import {
    Card,
    Statistic,
    Table,
    Button,
    Input,
    Select,
    Tag,
    Form,
    Divider,
    Spin,
    Modal,
    Upload,
    message,
    DatePicker,
    Menu,
    Layout
} from 'antd';
import {
    SearchOutlined,
    UploadOutlined,
    DownloadOutlined,
    EyeOutlined,
    PlusOutlined,
    FileTextOutlined,
    SettingOutlined
} from '@ant-design/icons';
import type {RangePickerProps} from 'antd/es/date-picker';
import dayjs from 'dayjs';
import mammoth from 'mammoth';
import {contractApi, statisticsApi} from './services/api';
import './index.css';

const {Sider, Content} = Layout;

// 类型定义
interface Contract {
    id: number;
    name: string;
    submitter: string;
    department: string;
    querySource: string;
    uploadTime: string;
    finishTime: string;
    documentUploader: string;
    highRisk: number;
    mediumRisk: number;
    lowRisk: number;
    status: string;
    contractNo?: string;
    contractType?: string;
    amount?: number;
    signDate?: string;
    depositRatio?: number;
    paymentMethod?: string;
    penaltyRatio?: number;
    deliveryPeriod?: number;
    sourceFile?: string;
}

// 格式化金额
const formatAmount = (amount: number) => {
    const formatter = new Intl.NumberFormat('zh-CN', {style: 'currency', currency: 'CNY'});
    return formatter.format(amount);
};

const App: React.FC = () => {
    const [currentPage, setCurrentPage] = useState('dashboard');
    const [selectedContract, setSelectedContract] = useState<any>({
        id: 0,
        name: '请选择合同',
        risks: []
    });
    const [contracts, setContracts] = useState<Contract[]>([]);
    const [loading, setLoading] = useState(false);
    const [searchText, setSearchText] = useState('');
    const [department, setDepartment] = useState('');
    const [querySource, setQuerySource] = useState('');
    const [riskLevel, setRiskLevel] = useState('');
    const [status, setStatus] = useState('');
    const [uploadTime, setUploadTime] = useState('');
    const [finishTime, setFinishTime] = useState('');
    const [currentPageNum, setCurrentPageNum] = useState(1);
    const [pageSize, setPageSize] = useState(8);
    const [total, setTotal] = useState(0);
    const [detailRiskLevel, setDetailRiskLevel] = useState('全部风险');
    const [detailSearchText, setDetailSearchText] = useState('');
    const [filteredRisks, setFilteredRisks] = useState<any[]>([]);
    const [statistics, setStatistics] = useState<any>({
        totalContracts: 13,
        totalRisks: 15,
        contracts2026: 13,
        risks2026: 15,
        contracts2025: 0,
        risks2025: 0
    });
    const [parsedContractContent, setParsedContractContent] = useState<string>('');
    const [parsing, setParsing] = useState<boolean>(false);
    const [previewUrl, setPreviewUrl] = useState<string>('');

    // 提交文档审查弹窗
    const [submitModalVisible, setSubmitModalVisible] = useState(false);
    const [uploadFileList, setUploadFileList] = useState<any[]>([]);
    const [submitForm] = Form.useForm();

    // 加载合同列表
    const loadContracts = async () => {
        setLoading(true);
        try {
            const response = await contractApi.getContractList({
                page: currentPageNum,
                pageSize: pageSize,
                name: searchText,
                department: department,
                querySource: querySource,
                riskLevel: riskLevel,
                uploadTime: uploadTime,
                finishTime: finishTime
            });
            // 先转换为unknown，再转换为我们自定义的类型
            const typedResponse = response as unknown as { code: number; data: Contract[]; total: number };
            if (typedResponse && typedResponse.code === 200) {
                setContracts(typedResponse.data || []);
                setTotal(typedResponse.total || 0);
            } else {
                setContracts([]);
                setTotal(0);
            }
        } catch (error) {
            console.error('加载合同列表失败:', error);
            setContracts([]);
            setTotal(0);
        } finally {
            setLoading(false);
        }
    };

    // 加载统计数据
    const loadStatistics = async () => {
        try {
            const response = await statisticsApi.getStatistics();
            // 先转换为unknown，再转换为我们自定义的类型
            const typedResponse = response as unknown as { code: number; data: any };
            if (typedResponse && typedResponse.code === 200) {
                setStatistics(typedResponse.data);
            }
        } catch (error) {
            console.error('加载统计数据失败:', error);
            // 失败时使用默认数据
            setStatistics({
                totalContracts: 13,
                totalRisks: 15,
                contracts2026: 13,
                risks2026: 15,
                contracts2025: 0,
                risks2025: 0
            });
        }
    };

    // 获取合同预览地址
    const getContractPreviewUrl = async (contractId: number) => {
        try {
            const response = await contractApi.getContractPreviewUrl(contractId);
            const typedResponse = response as unknown as { code: number; data: any };
            if (typedResponse && typedResponse.code === 200) {
                setPreviewUrl(typedResponse.data);
            }
        } catch (error) {
            console.error('获取预览地址失败:', error);
            setPreviewUrl('');
        }
    };

    // 解析合同文件
    const parseContractFile = async (contractId: number) => {
        setParsing(true);
        try {
            // 生成后端文件流URL
            const fileStreamUrl = `http://192.168.1.175:8084/api/contracts/${contractId}/file`;

            // 获取文件流
            const response = await fetch(fileStreamUrl);
            if (!response.ok) {
                throw new Error('Failed to fetch contract file');
            }

            // 读取文件内容为ArrayBuffer
            const arrayBuffer = await response.arrayBuffer();

            try {
                // 使用mammoth.js转换Word内容为HTML
                const result = await mammoth.convertToHtml({arrayBuffer: arrayBuffer});

                // 设置转换后的HTML内容
                setParsedContractContent(result.value);
                console.log('转换后的HTML内容:', result.value);
            } catch (parseError) {
                console.error('mammoth.js解析失败:', parseError);
                // 检查是否是.doc文件导致的错误
                const errorMessage = parseError instanceof Error ? parseError.message : String(parseError);
                if (errorMessage.includes('Can\'t find end of central directory')) {
                    // 这是.doc文件或其他不支持的格式
                    setParsedContractContent('<p>该合同文件为旧版.doc格式，不支持在线预览，请下载查看原始文件</p>');
                } else {
                    // 其他解析错误
                    setParsedContractContent('<p>合同文件格式不支持，请下载查看原始文件</p>');
                }
            }
        } catch (error) {
            console.error('解析合同文件失败:', error);
            setParsedContractContent('<p>合同文件解析失败，请下载查看原始文件</p>');
        } finally {
            setParsing(false);
        }
    };

    // 加载合同详情
    const loadContractDetail = async (contractId: number) => {
        setLoading(true);
        try {
            // 并行请求，提高加载速度
            const [detailResponse, risksResponse] = await Promise.all([
                contractApi.getContractById(contractId),
                contractApi.getContractRisks(contractId)
            ]);

            // 先转换为unknown，再转换为我们自定义的类型
            const typedDetailResponse = detailResponse as unknown as { code: number; data: any };
            const typedRisksResponse = risksResponse as unknown as { code: number; data: any };

            if (typedDetailResponse && typedDetailResponse.code === 200 && typedRisksResponse && typedRisksResponse.code === 200) {
                const risks = typedRisksResponse.data || [];
                // 计算风险概览数据
                const riskOverview = calculateRiskOverview(risks);

                const contractWithRisks = {
                    ...typedDetailResponse.data,
                    risks: risks,
                    highRisk: riskOverview.highRisk,
                    mediumRisk: riskOverview.mediumRisk,
                    lowRisk: riskOverview.lowRisk
                };
                setSelectedContract(contractWithRisks);
                filterRisks(risks);

                // 解析合同文件，使用URL.createObjectURL()创建本地URL
                await parseContractFile(contractId);
            } else {
                // API返回错误时显示空数据
                setSelectedContract({
                    id: contractId,
                    name: '合同详情加载失败',
                    highRisk: 0,
                    mediumRisk: 0,
                    lowRisk: 0,
                    risks: []
                });
                setFilteredRisks([]);
                setParsedContractContent('<p>合同详情加载失败</p>');
            }
        } catch (error) {
            console.error('加载合同详情失败:', error);
            // 网络错误时显示空数据
            setSelectedContract({
                id: contractId,
                name: '合同详情加载失败',
                highRisk: 0,
                mediumRisk: 0,
                lowRisk: 0,
                risks: []
            });
            setFilteredRisks([]);
            setParsedContractContent('<p>合同详情加载失败</p>');
        } finally {
            setLoading(false);
        }
    };

    // 过滤风险数据
    const filterRisks = (risks: any[]) => {
        let filtered = risks;

        // 按风险等级过滤
        if (detailRiskLevel !== '全部风险') {
            const levelMap: Record<string, string> = {
                '高风险': '高危',
                '中风险': '中危',
                '低风险': '低危'
            };
            const level = levelMap[detailRiskLevel];
            if (level) {
                filtered = filtered.filter(risk => risk.riskLevel === level);
            }
        }

        // 按搜索文本过滤
        if (detailSearchText) {
            const searchLower = detailSearchText.toLowerCase();
            filtered = filtered.filter(risk =>
                risk.riskType.toLowerCase().includes(searchLower) ||
                risk.regulationName.toLowerCase().includes(searchLower) ||
                risk.regulationClause.toLowerCase().includes(searchLower) ||
                risk.violationClause.toLowerCase().includes(searchLower) ||
                risk.suggestion.toLowerCase().includes(searchLower)
            );
        }

        setFilteredRisks(filtered);
    };

    // 计算风险概览数据
    const calculateRiskOverview = (risks: any[]) => {
        let highRisk = 0;
        let mediumRisk = 0;
        let lowRisk = 0;

        risks.forEach(risk => {
            switch (risk.riskLevel) {
                case '高危':
                    highRisk++;
                    break;
                case '中危':
                    mediumRisk++;
                    break;
                case '低危':
                    lowRisk++;
                    break;
                default:
                    break;
            }
        });

        return {highRisk, mediumRisk, lowRisk};
    };

    // 初始加载和分页变化时重新加载
    useEffect(() => {
        if (currentPage === 'dashboard') {
            loadContracts();
            loadStatistics();
        }
    }, [currentPageNum, pageSize]);

    // 组件加载时获取统计数据
    useEffect(() => {
        loadStatistics();
    }, []);

    // 当风险过滤条件变化时重新过滤
    useEffect(() => {
        if (currentPage === 'detail' && selectedContract.risks) {
            filterRisks(selectedContract.risks);
        }
    }, [detailRiskLevel, detailSearchText, selectedContract.risks, currentPage]);

    // 处理查看详情
    const handleViewDetail = (contract: any) => {
        loadContractDetail(contract.id);
        setCurrentPage('detail');
    };

    // 处理返回仪表盘
    const handleBackToDashboard = () => {
        setCurrentPage('dashboard');
        // 重置详情页的过滤条件
        setDetailRiskLevel('全部风险');
        setDetailSearchText('');
        setFilteredRisks([]);
        // 重置选中的合同
        setSelectedContract({
            id: 0,
            name: '请选择合同',
            risks: []
        });
    };

    // 风险等级标签颜色
    const getRiskLevelColor = (level: string) => {
        switch (level) {
            case '高危':
                return 'red';
            case '中危':
                return 'orange';
            case '低危':
                return 'green';
            default:
                return 'blue';
        }
    };

    // 风险等级标签文本
    const getRiskLevelText = (level: string) => {
        switch (level) {
            case 'high':
                return '高风险';
            case 'medium':
                return '中风险';
            case 'low':
                return '低风险';
            default:
                return '未知';
        }
    };

    // 处理搜索
    const handleSearch = () => {
        setCurrentPageNum(1); // 重置到第一页
        loadContracts();
    };

    // 处理重置
    const handleReset = () => {
        setSearchText('');
        setDepartment('');
        setQuerySource('');
        setRiskLevel('');
        setUploadTime('');
        setFinishTime('');
        setCurrentPageNum(1); // 重置到第一页
        loadContracts();
    };

    // 处理提交文档审查
    const handleSubmitReview = async () => {
        try {
            const formValues = await submitForm.validateFields();

            // 构建合同数据
            const contractData = {
                name: uploadFileList[0]?.name || '未命名合同',
                submitter: '唐文',
                department: '技术部',
                querySource: '直接查询',
                uploadTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
                finishTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
                documentUploader: '唐文',
                highRisk: 0,
                mediumRisk: 0,
                lowRisk: 0,
                status: '已完成'
            };

            // 调用后端接口提交合同
            const response = await contractApi.addContract(contractData);

            // 先转换为unknown，再转换为我们自定义的类型
            const typedResponse = response as unknown as { code: number; data: any };

            if (typedResponse && typedResponse.code === 200) {
                message.success('文档审查提交成功！');
                setSubmitModalVisible(false);
                submitForm.resetFields();
                setUploadFileList([]);
                loadContracts(); // 重新加载合同列表
            } else {
                message.error('文档审查提交失败，请稍后重试！');
            }
        } catch (error) {
            console.error('提交文档审查失败:', error);
            message.error('文档审查提交失败，请稍后重试！');
        }
    };

    // 处理文件上传
    const handleFileUpload = (file: any) => {
        // 这里只是模拟文件上传，实际项目中需要调用后端接口
        setUploadFileList([file]);
        // 设置合同名称为上传的文件名称
        submitForm.setFieldsValue({name: file.name});
        return false; // 阻止自动上传
    };

    // 处理分页变化
    const handlePageChange = (page: number, size: number) => {
        setCurrentPageNum(page);
        setPageSize(size);
    };

    // 处理忽略风险
    const handleIgnoreRisk = async (riskId: number) => {
        try {
            // 调用后端接口更新风险状态
            const response = await fetch(`http://192.168.1.175:8084/api/risks/${riskId}/status`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({status: 1}) // 1表示忽略
            });

            if (response.ok) {
                message.success('风险已忽略');
                // 重新加载合同详情，更新风险状态
                loadContractDetail(selectedContract.id);
            } else {
                message.error('忽略风险失败，请稍后重试');
            }
        } catch (error) {
            console.error('忽略风险失败:', error);
            message.error('忽略风险失败，请稍后重试');
        }
    };

    // 仪表盘页面
    const DashboardPage = () => (
        <div>
            <div className="header">
                <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
                    <div className="header-title">文件导入启动AI风险扫描</div>
                    <div className="header-right">
                        <div className="logo">IN-ORDER</div>
                    </div>
                </div>
            </div>

            <div className="content">
                <div className="dashboard-stats">
                    <Card className="dashboard-stat-card">
                        <Statistic title="总计审查文件数" value={statistics.totalContracts}
                                   suffix={<Tag color="green">+100% 较上月</Tag>}/>
                    </Card>
                    <Card className="dashboard-stat-card">
                        <Statistic title="发现风险数" value={statistics.totalRisks}
                                   suffix={<Tag color="green">+100% 较上月</Tag>}/>
                    </Card>
                    <Card className="dashboard-stat-card">
                        <Statistic title="2026年审查文件数" value={statistics.contracts2026}
                                   suffix={<Tag color="green">+100% 较去年</Tag>}/>
                    </Card>
                    <Card className="dashboard-stat-card">
                        <Statistic title="2026年发现风险数" value={statistics.risks2026}
                                   suffix={<Tag color="green">+100% 较去年</Tag>}/>
                    </Card>
                </div>

                <div className="search-bar">
                    <Form layout="inline">
                        <Form.Item>
                            <Select
                                placeholder="部门"
                                className="filter-item"
                                value={department}
                                onChange={setDepartment}
                                options={[
                                    {value: '', label: '全部部门'},
                                    {value: '销售部', label: '销售部'},
                                    {value: '采购部', label: '采购部'},
                                    {value: '技术部', label: '技术部'},
                                    {value: '行政部', label: '行政部'},
                                    {value: '人力资源部', label: '人力资源部'},
                                    {value: '供应链', label: '供应链'},
                                    {value: '市场部', label: '市场部'},
                                    {value: '管理部', label: '管理部'},
                                    {value: '工程部', label: '工程部'}
                                ]}
                            />
                        </Form.Item>
                        <Form.Item>
                            <Select
                                placeholder="查询来源"
                                className="filter-item"
                                value={querySource}
                                onChange={setQuerySource}
                                options={[
                                    {value: '', label: '全部来源'},
                                    {value: '直接查询', label: '直接查询'},
                                    {value: '知识库自动审查', label: '知识库自动审查'},
                                    {value: '钉钉自动审查', label: '钉钉自动审查'}
                                ]}
                            />
                        </Form.Item>
                        <Form.Item>
                            <Select
                                placeholder="风险等级"
                                className="filter-item"
                                value={riskLevel}
                                onChange={setRiskLevel}
                                options={[
                                    {value: '', label: '全部等级'},
                                    {value: 'high', label: '高风险'},
                                    {value: 'medium', label: '中风险'},
                                    {value: 'low', label: '低风险'}
                                ]}
                            />
                        </Form.Item>
                        <Form.Item>
                            <DatePicker
                                placeholder="上传时间"
                                className="filter-item"
                                style={{width: 180}}
                                onChange={(date) => setUploadTime(date ? date.format('YYYY-MM-DD HH:mm:ss') : '')}
                            />
                        </Form.Item>
                        <Form.Item>
                            <DatePicker
                                placeholder="完结时间"
                                className="filter-item"
                                style={{width: 180}}
                                onChange={(date) => setFinishTime(date ? date.format('YYYY-MM-DD HH:mm:ss') : '')}
                            />
                        </Form.Item>
                        <Form.Item>
                            <Input
                                placeholder="搜索文件名称"
                                prefix={<SearchOutlined/>}
                                className="search-input"
                                value={searchText}
                                onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSearchText(e.target.value)}
                            />
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" onClick={handleSearch}>搜索</Button>
                        </Form.Item>
                        <Form.Item>
                            <Button onClick={handleReset}>重置</Button>
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" icon={<UploadOutlined/>} onClick={() => setSubmitModalVisible(true)}>
                                提交文件审查
                            </Button>
                        </Form.Item>
                    </Form>
                </div>

                <Spin spinning={loading} tip="加载中...">
                    <Table
                        dataSource={contracts}
                        columns={[
                            {
                                title: '序号',
                                dataIndex: 'id',
                                key: 'id'
                            },
                            {
                                title: '文件名称',
                                dataIndex: 'name',
                                key: 'name',
                                render: (text: string) => <a href="#">{text}</a>
                            },
                            {
                                title: '审查发起人',
                                dataIndex: 'submitter',
                                key: 'submitter'
                            },
                            {
                                title: '查询来源',
                                dataIndex: 'querySource',
                                key: 'querySource'
                            },
                            {
                                title: '所属部门',
                                dataIndex: 'department',
                                key: 'department'
                            },
                            {
                                title: '上传时间',
                                dataIndex: 'uploadTime',
                                key: 'uploadTime'
                            },
                            {
                                title: '完结时间',
                                dataIndex: 'finishTime',
                                key: 'finishTime'
                            },
                            {
                                title: 'AI初审结果',
                                dataIndex: 'status',
                                key: 'status',
                                render: (status: string) => <Tag
                                    color={status === '已完成' ? 'green' : 'blue'}>{status}</Tag>
                            },
                            {
                                title: '风险项',
                                dataIndex: ['highRisk', 'mediumRisk', 'lowRisk'],
                                key: 'result',
                                render: (_, record: any) => (
                                    <div>
                                        <Tag color="red">高风险 {record.highRisk}</Tag>
                                        <Tag color="orange">中风险 {record.mediumRisk}</Tag>
                                        <Tag color="green">低风险 {record.lowRisk}</Tag>
                                    </div>
                                )
                            },
                            {
                                title: '操作',
                                key: 'action',
                                render: (_, record: any) => (
                                    <Button
                                        type="link"
                                        icon={<EyeOutlined/>}
                                        onClick={() => handleViewDetail(record)}
                                    >
                                        查看详情
                                    </Button>
                                )
                            }
                        ]}
                        pagination={{
                            current: currentPageNum,
                            pageSize: pageSize,
                            total: total,
                            showSizeChanger: true,
                            pageSizeOptions: ['8', '16', '24'],
                            showTotal: (total) => `显示第 ${(currentPageNum - 1) * pageSize + 1} 至 ${Math.min(currentPageNum * pageSize, total)} 条，共 ${total} 条结果`,
                            onChange: handlePageChange
                        }}
                    />
                </Spin>
            </div>
        </div>
    );

    // 合同审查详情页面
    const DetailPage = () => (
        <div>
            <div className="header">
                <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
                    <div style={{display: 'flex', alignItems: 'center', gap: 16}}>
                        <Button icon={<EyeOutlined/>} onClick={handleBackToDashboard}>
                            返回列表
                        </Button>
                        <div className="header-title">文件导入启动AI风险扫描结果展示</div>
                    </div>
                    <div className="header-right">
                        <div className="logo">IN-ORDER</div>
                    </div>
                </div>
            </div>

            <div className="content">
                <Spin spinning={loading} tip="加载中...">
                    {/* 顶部合同信息 */}
                    <div style={{
                        marginBottom: 20,
                        padding: 16,
                        backgroundColor: '#fff',
                        borderRadius: 8,
                        boxShadow: '0 2px 8px rgba(0,0,0,0.09)'
                    }}>
                        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
                            <div>
                                <h2 style={{
                                    margin: 0,
                                    fontSize: '24px',
                                    fontWeight: 'bold',
                                    color: '#333'
                                }}>{selectedContract.name}</h2>
                                <div style={{marginTop: 8, color: '#666'}}>
                                    <span style={{marginRight: 24}}>合同编号: {selectedContract.contractNo || ''}</span>
                                    <span style={{marginRight: 24}}>上传日期: {selectedContract.uploadTime || ''}</span>
                                    <span>文档上传人: {selectedContract.documentUploader || ''}</span>
                                </div>
                            </div>
                            <div style={{display: 'flex', gap: 16}}>
                                <Button type="primary">重新审查</Button>
                            </div>
                        </div>
                    </div>

                    {/* 风险概览 */}
                    <div style={{
                        marginBottom: 20,
                        padding: 16,
                        backgroundColor: '#fff',
                        borderRadius: 8,
                        boxShadow: '0 2px 8px rgba(0,0,0,0.09)'
                    }}>
                        <h3 style={{
                            margin: '0 0 16px 0',
                            fontSize: '18px',
                            fontWeight: 'bold',
                            color: '#333'
                        }}>风险概览</h3>
                        <div style={{display: 'flex', gap: 16, flexWrap: 'wrap'}}>
                            {/* 计算风险总数 */}
                            {(() => {
                                const totalRisk = (selectedContract.highRisk || 0) + (selectedContract.mediumRisk || 0) + (selectedContract.lowRisk || 0);
                                return (
                                    <>
                                        {/* 风险总数 */}
                                        <div style={{flex: 1, minWidth: 200}}>
                                            <div style={{display: 'flex', alignItems: 'center', marginBottom: 8}}>
                                                <div style={{
                                                    fontSize: '14px',
                                                    marginRight: 12,
                                                    color: '#1890ff'
                                                }}>风险总数: {totalRisk}</div>
                                            </div>
                                            <div style={{
                                                flex: 1,
                                                height: 8,
                                                backgroundColor: '#f0f0f0',
                                                borderRadius: 4,
                                                overflow: 'hidden'
                                            }}>
                                                <div style={{
                                                    width: totalRisk > 0 ? '100%' : '0%',
                                                    height: '100%',
                                                    backgroundColor: '#1890ff',
                                                    borderRadius: 4
                                                }}></div>
                                            </div>
                                        </div>
                                        {/* 高风险 */}
                                        <div style={{flex: 1, minWidth: 200}}>
                                            <div style={{display: 'flex', alignItems: 'center', marginBottom: 8}}>
                                                <div style={{
                                                    fontSize: '14px',
                                                    marginRight: 12,
                                                    color: '#ff4d4f'
                                                }}>高风险: {selectedContract.highRisk || 0}</div>
                                            </div>
                                            <div style={{
                                                flex: 1,
                                                height: 8,
                                                backgroundColor: '#f0f0f0',
                                                borderRadius: 4,
                                                overflow: 'hidden'
                                            }}>
                                                <div style={{
                                                    width: totalRisk > 0 ? `${Math.round(((selectedContract.highRisk || 0) / totalRisk) * 100)}%` : '0%',
                                                    height: '100%',
                                                    backgroundColor: '#ff4d4f',
                                                    borderRadius: 4
                                                }}></div>
                                            </div>
                                        </div>
                                        {/* 中风险 */}
                                        <div style={{flex: 1, minWidth: 200}}>
                                            <div style={{display: 'flex', alignItems: 'center', marginBottom: 8}}>
                                                <div style={{
                                                    fontSize: '14px',
                                                    marginRight: 12,
                                                    color: '#fa8c16'
                                                }}>中风险: {selectedContract.mediumRisk || 0}</div>
                                            </div>
                                            <div style={{
                                                flex: 1,
                                                height: 8,
                                                backgroundColor: '#f0f0f0',
                                                borderRadius: 4,
                                                overflow: 'hidden'
                                            }}>
                                                <div style={{
                                                    width: totalRisk > 0 ? `${Math.round(((selectedContract.mediumRisk || 0) / totalRisk) * 100)}%` : '0%',
                                                    height: '100%',
                                                    backgroundColor: '#fa8c16',
                                                    borderRadius: 4
                                                }}></div>
                                            </div>
                                        </div>
                                        {/* 低风险 */}
                                        <div style={{flex: 1, minWidth: 200}}>
                                            <div style={{display: 'flex', alignItems: 'center', marginBottom: 8}}>
                                                <div style={{
                                                    fontSize: '14px',
                                                    marginRight: 12,
                                                    color: '#52c41a'
                                                }}>低风险: {selectedContract.lowRisk || 0}</div>
                                            </div>
                                            <div style={{
                                                flex: 1,
                                                height: 8,
                                                backgroundColor: '#f0f0f0',
                                                borderRadius: 4,
                                                overflow: 'hidden'
                                            }}>
                                                <div style={{
                                                    width: totalRisk > 0 ? `${Math.round(((selectedContract.lowRisk || 0) / totalRisk) * 100)}%` : '0%',
                                                    height: '100%',
                                                    backgroundColor: '#52c41a',
                                                    borderRadius: 4
                                                }}></div>
                                            </div>
                                        </div>
                                    </>
                                );
                            })()}
                        </div>
                    </div>

                    {/* 主要内容区域 */}
                    <div style={{display: 'flex', gap: 20}}>
                        {/* 左侧：合同内容预览 */}
                        <div style={{
                            flex: 2,
                            backgroundColor: '#fff',
                            padding: 20,
                            borderRadius: 8,
                            boxShadow: '0 2px 8px rgba(0,0,0,0.09)',
                            height: '80vh',
                            overflow: 'auto'
                        }}>
                            <h3 style={{
                                margin: '0 0 16px 0',
                                fontSize: '18px',
                                fontWeight: 'bold',
                                color: '#333'
                            }}>合同内容</h3>
                            <div style={{
                                border: '1px solid #f0f0f0',
                                borderRadius: 4,
                                padding: 20,
                                backgroundColor: '#fafafa'
                            }}>
                                {selectedContract.id ? (
                                    <div>
                                        {parsing ? (
                                            <div style={{textAlign: 'center', padding: 40}}>
                                                <p style={{color: '#999'}}>合同文件加载中...</p>
                                            </div>
                                        ) : (
                                            <div style={{
                                                border: '1px solid #e8e8e8',
                                                borderRadius: 4,
                                                padding: 20,
                                                backgroundColor: '#fff',
                                                minHeight: '700px'
                                            }}>
                                                {parsing ? (
                                                    <div style={{textAlign: 'center', padding: 40}}>
                                                        <p style={{color: '#1890ff'}}>合同文件加载中...</p>
                                                    </div>
                                                ) : parsedContractContent ? (
                                                    <div className="mammoth-content" style={{
                                                        border: '1px solid #e8e8e8',
                                                        borderRadius: 4,
                                                        padding: 20,
                                                        backgroundColor: '#fafafa',
                                                        minHeight: '600px',
                                                        overflow: 'auto'
                                                    }}>
                                                        <div dangerouslySetInnerHTML={{__html: parsedContractContent}}/>
                                                    </div>
                                                ) : (
                                                    <div style={{textAlign: 'center', padding: 40}}>
                                                        <p style={{color: '#999'}}>合同文件加载失败，请下载查看原始文件</p>
                                                    </div>
                                                )}
                                            </div>
                                        )}
                                        <div style={{marginTop: 16, textAlign: 'center'}}>
                                            <a
                                                href={previewUrl || `http://192.168.1.175:8081/api/contracts/${selectedContract.id}/file`}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                style={{
                                                    display: 'inline-block',
                                                    padding: '8px 16px',
                                                    backgroundColor: '#1890ff',
                                                    color: '#fff',
                                                    textDecoration: 'none',
                                                    borderRadius: 4,
                                                    marginRight: 12
                                                }}
                                            >
                                                打开源文件
                                            </a>
                                            <a
                                                href={previewUrl || `http://192.168.1.175:8081/api/contracts/${selectedContract.id}/file`}
                                                download
                                                style={{
                                                    display: 'inline-block',
                                                    padding: '8px 16px',
                                                    backgroundColor: '#52c41a',
                                                    color: '#fff',
                                                    textDecoration: 'none',
                                                    borderRadius: 4
                                                }}
                                            >
                                                下载文件
                                            </a>
                                        </div>
                                    </div>
                                ) : (
                                    <p style={{color: '#999', textAlign: 'center', padding: 40}}>合同内容加载中...</p>
                                )}
                            </div>
                        </div>

                        {/* 右侧：风险详情 */}
                        <div style={{
                            flex: 1,
                            backgroundColor: '#fff',
                            padding: 20,
                            borderRadius: 8,
                            boxShadow: '0 2px 8px rgba(0,0,0,0.09)',
                            height: '80vh',
                            overflow: 'auto'
                        }}>
                            <h3 style={{
                                margin: '0 0 16px 0',
                                fontSize: '18px',
                                fontWeight: 'bold',
                                color: '#333'
                            }}>风险详情</h3>

                            {/* 风险过滤和搜索 */}
                            <div style={{marginBottom: 20, display: 'flex', gap: 12, alignItems: 'center'}}>
                                <Select
                                    value={detailRiskLevel}
                                    style={{width: 120}}
                                    onChange={(value) => setDetailRiskLevel(value)}
                                >
                                    <Select.Option value="全部风险">全部风险</Select.Option>
                                    <Select.Option value="高风险">高风险</Select.Option>
                                    <Select.Option value="中风险">中风险</Select.Option>
                                    <Select.Option value="低风险">低风险</Select.Option>
                                </Select>
                                <Input
                                    placeholder="搜索风险点"
                                    prefix={<SearchOutlined/>}
                                    style={{flex: 1}}
                                    value={detailSearchText}
                                    onChange={(e) => setDetailSearchText(e.target.value)}
                                />
                            </div>

                            {/* 风险详情列表 */}
                            <div>
                                {filteredRisks.map((risk: any) => (
                                    <div key={risk.id} style={{
                                        marginBottom: 16,
                                        padding: 16,
                                        border: '1px solid #f0f0f0',
                                        borderRadius: 4,
                                        backgroundColor: risk.status === 1 ? '#f0f5ff' : '#fafafa',
                                        opacity: risk.status === 1 ? 0.8 : 1
                                    }}>
                                        <div style={{
                                            display: 'flex',
                                            justifyContent: 'space-between',
                                            alignItems: 'center',
                                            marginBottom: 12
                                        }}>
                                            <div style={{display: 'flex', alignItems: 'center'}}>
                                                <Tag key={risk.id + '-tag'}
                                                     color={risk.status === 1 ? 'gray' : getRiskLevelColor(risk.riskLevel)}
                                                     style={{marginRight: 8}}>
                                                    {risk.status === 1 ? `${risk.riskLevel} (已忽略)` : risk.riskLevel}
                                                </Tag>
                                                <span style={{
                                                    fontWeight: 'bold',
                                                    color: risk.status === 1 ? '#666' : '#333'
                                                }}>{risk.riskType}</span>
                                            </div>
                                            {risk.status !== 1 && (
                                                <Button
                                                    key={risk.id + '-button'}
                                                    type="link"
                                                    size="small"
                                                    onClick={() => handleIgnoreRisk(risk.id)}
                                                >
                                                    忽略风险
                                                </Button>
                                            )}
                                        </div>
                                        <div style={{marginBottom: 8}}>
                                            <span style={{
                                                fontWeight: 'bold',
                                                color: risk.status === 1 ? '#666' : '#333'
                                            }}>法规名称:</span>
                                            <span style={{
                                                marginLeft: 8,
                                                color: risk.status === 1 ? '#999' : '#666'
                                            }}>{risk.regulationName}</span>
                                        </div>
                                        <div style={{marginBottom: 8}}>
                                            <span style={{
                                                fontWeight: 'bold',
                                                color: risk.status === 1 ? '#666' : '#333'
                                            }}>法规条目:</span>
                                            <span style={{
                                                marginLeft: 8,
                                                color: risk.status === 1 ? '#999' : '#666'
                                            }}>{risk.regulationClause}</span>
                                        </div>
                                        <div style={{marginBottom: 8}}>
                                            <span style={{
                                                fontWeight: 'bold',
                                                color: risk.status === 1 ? '#666' : '#333'
                                            }}>违规条款 (原文摘要):</span>
                                            <span style={{
                                                marginLeft: 8,
                                                color: risk.status === 1 ? '#999' : '#666'
                                            }}>{risk.violationClause}</span>
                                        </div>
                                        <div style={{marginBottom: 8}}>
                                            <span style={{
                                                fontWeight: 'bold',
                                                color: risk.status === 1 ? '#666' : '#333'
                                            }}>违规依据:</span>
                                            <span style={{
                                                marginLeft: 8,
                                                color: risk.status === 1 ? '#999' : '#666'
                                            }}>{risk.violationBasis}</span>
                                        </div>
                                        <div style={{marginBottom: 8}}>
                                            <span style={{
                                                fontWeight: 'bold',
                                                color: risk.status === 1 ? '#666' : '#333'
                                            }}>风险详情:</span>
                                            <span style={{
                                                marginLeft: 8,
                                                color: risk.status === 1 ? '#999' : '#666'
                                            }}>{risk.description}</span>
                                        </div>
                                        <div>
                                            <span style={{
                                                fontWeight: 'bold',
                                                color: risk.status === 1 ? '#666' : '#333'
                                            }}>修改建议:</span>
                                            <span style={{
                                                marginLeft: 8,
                                                color: risk.status === 1 ? '#999' : '#666'
                                            }}>{risk.suggestion}</span>
                                        </div>
                                    </div>
                                ))}
                                {filteredRisks.length === 0 && (
                                    <div style={{textAlign: 'center', padding: 40, color: '#999'}}>
                                        未找到匹配的风险点
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                </Spin>
            </div>
        </div>
    );

    // 提交文档审查弹窗
    const SubmitReviewModal = () => (
        <Modal
            title="提交文档审查"
            open={submitModalVisible}
            onCancel={() => setSubmitModalVisible(false)}
            footer={[
                <Button key="cancel" onClick={() => setSubmitModalVisible(false)}>
                    取消
                </Button>,
                <Button key="submit" type="primary" onClick={handleSubmitReview}>
                    提交
                </Button>
            ]}
            width={600}
            onOk={() => handleSubmitReview()}
        >
            <Form form={submitForm} layout="vertical">
                <Form.Item
                    label="文件上传"
                    name="file"
                    rules={[{required: true, message: '请上传合同文件'}]}
                >
                    <Upload
                        fileList={uploadFileList}
                        customRequest={handleFileUpload}
                        listType="text"
                        maxCount={1}
                        onRemove={() => {
                            setUploadFileList([]);
                            submitForm.setFieldsValue({name: ''});
                        }}
                    >
                        <Button icon={<UploadOutlined/>}>点击上传</Button>
                    </Upload>
                </Form.Item>
            </Form>
        </Modal>
    );

    // 风险模块页面
    const RiskModulePage = () => {
        const [regulations, setRegulationsv ] = useState<any[]>([]);
        const [regulationLoading, setRegulationLoading] = useState(false);
        const [searchText, setSearchText] = useState('');
        const [riskLevel, setRiskLevel] = useState('');
        const [status, setStatus] = useState('');
        const [DocumentClassification, setDocumentClassification] = useState('');
        const [addModalVisible, setAddModalVisible] = useState(false);
        const [editModalVisible, setEditModalVisible] = useState(false);
        const [currentRegulation, setCurrentRegulation] = useState<any>({});
        const [addForm] = Form.useForm();
        const [editForm] = Form.useForm();
        const [activeDocumentCategory, setActiveDocumentCategory] = useState('全部');
        const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

        // 加载规章制度列表
        const loadRegulations = async () => {
            setRegulationLoading(true);
            try {
                const response = await fetch('http://192.168.1.175:8084/api/regulations?page=1&pageSize=100');
                if (response.ok) {
                    const data = await response.json();
                    if (data.code === 200) {
                        setRegulations(data.data);
                    }
                }
            } catch (error) {
                console.error('加载规章制度失败:', error);
                message.error('加载规章制度失败，请稍后重试');
            } finally {
                setRegulationLoading(false);
            }
        };

        // 处理新增规章制度
        const handleAddRegulation = () => {
            addForm.resetFields();
            setAddModalVisible(true);
        };

        // 处理编辑规章制度
        const handleEditRegulation = (regulation: any) => {
            setCurrentRegulation(regulation);
            editForm.setFieldsValue({
                ruleNo: regulation.ruleNo,
                ruleName: regulation.ruleName,
                regulationName: regulation.regulationName,
                regulationClause: regulation.regulationClause,
                riskLevel: regulation.riskLevel,
                status: regulation.status,
                effectiveTime: regulation.effectiveTime ? dayjs(regulation.effectiveTime) : undefined
            });
            setEditModalVisible(true);
        };

        // 处理删除规章制度
        const handleDeleteRegulation = async (regulationId: number) => {
            if (window.confirm('确定要删除这个规章制度吗？')) {
                try {
                    const response = await fetch(`http://192.168.1.175:8084/api/regulations/${regulationId}`, {
                        method: 'DELETE',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });

                    if (response.ok) {
                        const data = await response.json();
                        if (data.code === 200) {
                            message.success('规章制度已删除');
                            loadRegulations();
                        } else {
                            message.error('删除失败：' + (data.message || '未知错误'));
                        }
                    } else {
                        message.error('删除失败：网络请求错误');
                    }
                } catch (error) {
                    console.error('删除规章制度失败:', error);
                    message.error('删除规章制度失败，请稍后重试');
                }
            }
        };

        // 处理表格行选择
        const rowSelection = {
            selectedRowKeys,
            onChange: (selectedKeys: React.Key[]) => {
                setSelectedRowKeys(selectedKeys);
            },
            selections: [
                Table.SELECTION_ALL,
                Table.SELECTION_INVERT,
                Table.SELECTION_NONE,
            ],
        };

        // 批量删除功能
        const handleBatchDelete = async () => {
            if (selectedRowKeys.length === 0) {
                message.warning('请先选择要删除的记录');
                return;
            }
            
            if (window.confirm(`确定要删除选中的 ${selectedRowKeys.length} 条记录吗？`)) {
                try {
                    // 批量删除选中的记录
                    const deletePromises = selectedRowKeys.map(key => 
                        fetch(`http://192.168.1.175:8084/api/regulations/${key}`, {
                            method: 'DELETE',
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        })
                    );
                    
                    const responses = await Promise.all(deletePromises);
                    const successCount = responses.filter(response => response.ok).length;
                    
                    if (successCount === selectedRowKeys.length) {
                        message.success(`成功删除 ${successCount} 条记录`);
                        setSelectedRowKeys([]);
                        loadRegulations();
                    } else {
                        message.warning(`部分删除成功，成功 ${successCount}/${selectedRowKeys.length} 条`);
                        setSelectedRowKeys([]);
                        loadRegulations();
                    }
                } catch (error) {
                    console.error('批量删除失败:', error);
                    message.error('批量删除失败，请稍后重试');
                }
            }
        };

        // 只在组件首次加载时调用一次loadRegulations函数
        useEffect(() => {
            loadRegulations();
        }, []);

        // 处理新增规章制度提交
        const handleAddSubmit = async () => {
            try {
                const values = await addForm.validateFields();

                const regulationData = {
                    ruleNo: values.ruleNo,
                    ruleName: values.ruleName,
                    regulationName: values.regulationName,
                    regulationClause: values.regulationClause,
                    riskLevel: values.riskLevel,
                    status: values.status,
                    effectiveTime: values.effectiveTime ? values.effectiveTime.format('YYYY-MM-DD HH:mm:ss') : null
                };

                const response = await fetch('http://192.168.1.175:8084/api/regulations', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(regulationData)
                });

                if (response.ok) {
                    const data = await response.json();
                    if (data.code === 200) {
                        message.success('规章制度新增成功');
                        setAddModalVisible(false);
                        addForm.resetFields();
                        loadRegulations();
                    } else {
                        message.error('新增失败：' + (data.message || '未知错误'));
                    }
                } else {
                    message.error('新增失败：网络请求错误');
                }
            } catch (error) {
                console.error('新增规章制度失败:', error);
                message.error('新增规章制度失败，请稍后重试');
            }
        };

        // 处理编辑规章制度提交
        const handleEditSubmit = async () => {
            try {
                const values = await editForm.validateFields();

                const regulationData = {
                    ruleNo: values.ruleNo,
                    ruleName: values.ruleName,
                    regulationName: values.regulationName,
                    regulationClause: values.regulationClause,
                    riskLevel: values.riskLevel,
                    status: values.status,
                    effectiveTime: values.effectiveTime ? values.effectiveTime.format('YYYY-MM-DD HH:mm:ss') : null
                };

                const response = await fetch(`http://192.168.1.175:8084/api/regulations/${currentRegulation.id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(regulationData)
                });

                if (response.ok) {
                    const data = await response.json();
                    if (data.code === 200) {
                        message.success('规章制度编辑成功');
                        setEditModalVisible(false);
                        editForm.resetFields();
                        loadRegulations();
                    } else {
                        message.error('编辑失败：' + (data.message || '未知错误'));
                    }
                } else {
                    message.error('编辑失败：网络请求错误');
                }
            } catch (error) {
                console.error('编辑规章制度失败:', error);
                message.error('编辑规章制度失败，请稍后重试');
            }
        };

        // 过滤规章制度
        const filteredRegulations = regulations.filter(regulation => {
            const matchesSearch = !searchText ||
                regulation.ruleNo.toLowerCase().includes(searchText.toLowerCase()) ||
                regulation.ruleName.toLowerCase().includes(searchText.toLowerCase()) ||
                regulation.regulationName.toLowerCase().includes(searchText.toLowerCase());
            const matchesRiskLevel = !riskLevel || regulation.riskLevel === riskLevel;
            const matchesStatus = !status || regulation.status.toString() === status;
            return matchesSearch && matchesRiskLevel && matchesStatus;
        });

        return (
            <div>
                <div className="header">
                    <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
                        <div className="header-title">风险设置管理</div>
                        <div className="header-right">
                            <div className="logo">IN-ORDER</div>
                        </div>
                    </div>
                </div>
                {/*统计tab*/}
                {/*    <div className="dashboard-stats">*/}
                {/*        <Card className="dashboard-stat-card">*/}
                {/*            <Statistic title="合同协议" value="9"*/}
                {/*                       suffix={<Tag color="green">+100% 较上月</Tag>}/>*/}
                {/*        </Card>*/}
                {/*        <Card className="dashboard-stat-card">*/}
                {/*            <Statistic title="财务文档" value="3"*/}
                {/*                       suffix={<Tag color="green">+10% 较上月</Tag>}/>*/}
                {/*        </Card>*/}
                {/*        <Card className="dashboard-stat-card">*/}
                {/*            <Statistic title="人事文档" value="2"*/}
                {/*                       suffix={<Tag color="green">+30% 较去年</Tag>}/>*/}
                {/*        </Card>*/}
                {/*        <Card className="dashboard-stat-card">*/}
                {/*            <Statistic title="其他" value="100"*/}
                {/*                       suffix={<Tag color="green">+100% 较去年</Tag>}/>*/}
                {/*        </Card>*/}
                {/*    </div>*/}
                {/*添加切换tab，文档分类*/}
                <div className="nav-menu" style={{marginBottom: 20}}>
                    <div style={{
                        display: 'flex',
                        gap: 12,
                        padding: '12px 20px',
                        backgroundColor: '#fff',
                        borderRadius: 8,
                        boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
                        border: '1px solid #f0f0f0',
                        marginLeft: '24px',
                    }}>
                        <Button
                            type={activeDocumentCategory === '全部' ? 'primary' : 'default'}
                            onClick={() => setActiveDocumentCategory('全部')}
                            size="large"
                            style={{
                                borderRadius: 6,
                                fontWeight: '500',
                                minWidth: 80,
                                height: 40
                            }}
                        >
                            全部
                        </Button>
                        <Button 
                            type={activeDocumentCategory === '合同协议' ? 'primary' : 'default'}
                            onClick={() => setActiveDocumentCategory('合同协议')}
                            size="large"
                            style={{
                                borderRadius: 6,
                                fontWeight: '500',
                                minWidth: 100,
                                height: 40
                            }}
                        >
                            合同协议
                        </Button>
                        <Button 
                            type={activeDocumentCategory === '财务文档' ? 'primary' : 'default'}
                            onClick={() => setActiveDocumentCategory('财务文档')}
                            size="large"
                            style={{
                                borderRadius: 6,
                                fontWeight: '500',
                                minWidth: 100,
                                height: 40
                            }}
                        >
                            财务文档
                        </Button>
                        <Button 
                            type={activeDocumentCategory === '人事文档' ? 'primary' : 'default'}
                            onClick={() => setActiveDocumentCategory('人事文档')}
                            size="large"
                            style={{
                                borderRadius: 6,
                                fontWeight: '500',
                                minWidth: 100,
                                height: 40
                            }}
                        >
                            人事文档
                        </Button>
                    </div>
                </div>
                <div className="content">
                    {/* 筛选区域 */}
                    <div style={{marginBottom: 20, padding: 16, backgroundColor: '#fafafa', borderRadius: 4}}>
                        <Form layout="inline">
                            <Form.Item>
                                <Input
                                    placeholder="搜索规则编号、名称或法规"
                                    prefix={<SearchOutlined/>}
                                    style={{width: 300}}
                                    value={searchText}
                                    onChange={(e) => setSearchText(e.target.value)}
                                />
                            </Form.Item>
                            <Form.Item>
                                <Select
                                    placeholder="风险等级"
                                    style={{width: 120}}
                                    value={riskLevel}
                                    onChange={(value) => setRiskLevel(value)}
                                    options={[
                                        {value: '', label: '全部等级'},
                                        {value: '高危', label: '高危'},
                                        {value: '中危', label: '中危'},
                                        {value: '低危', label: '低危'}
                                    ]}
                                />
                            </Form.Item>
                            <Form.Item>
                                <Select
                                    placeholder="生效状态"
                                    style={{width: 120}}
                                    value={status}
                                    onChange={(value) => setStatus(value)}
                                    options={[
                                        {value: '', label: '全部状态'},
                                        {value: '1', label: '已生效'},
                                        {value: '0', label: '未生效'}
                                    ]}
                                />
                            </Form.Item>
                           {/* <Form.Item>
                                <Select
                                    placeholder="文档分类"
                                    style={{width: 120}}
                                    value={DocumentClassification}
                                    onChange={(value) => setDocumentClassification(value)}
                                    options={[
                                        {value: '', label: '全部分类'},
                                        {value: '1', label: '合同协议'},
                                        {value: '0', label: '财务文档'}
                                    ]}
                                />
                            </Form.Item>*/}
                            <Form.Item>
                                <Button type="primary" onClick={loadRegulations}>
                                    搜索
                                </Button>
                            </Form.Item>
                            <Form.Item>
                                <Button onClick={() => {
                                    setSearchText('');
                                    setRiskLevel('');
                                    setStatus('');
                                }}>
                                    重置
                                </Button>
                            </Form.Item>
                            <Form.Item>
                                <Button type="primary" icon={<PlusOutlined/>} onClick={handleAddRegulation}>
                                    新增规章制度
                                </Button>
                                <Button type="primary" style={{marginLeft: 8}} icon={<UploadOutlined/>} >
                                    批量导入
                                </Button>
                                <Button type="primary" style={{marginLeft: 8}} icon={<DownloadOutlined/>} >
                                    批量导出
                                </Button>
                            </Form.Item>
                        </Form>
                    </div>

                    <div style={{marginBottom: 16, display: 'flex', gap: 8}}>
                        <Button 
                            type="primary" 
                            danger 
                            disabled={selectedRowKeys.length === 0}
                            onClick={handleBatchDelete}
                        >
                            批量删除 ({selectedRowKeys.length})
                        </Button>
                        <Button 
                            type="default"
                            disabled={selectedRowKeys.length === 0}
                            onClick={() => message.info(`已选择 ${selectedRowKeys.length} 条记录`)}
                        >
                            批量导出
                        </Button>
                    </div>
                    
                    <Spin spinning={regulationLoading} tip="加载中...">
                        <Table
                            rowSelection={rowSelection}
                            dataSource={filteredRegulations}
                            columns={[
                                {
                                    title: '序号',
                                    dataIndex: 'id',
                                    key: 'id'
                                },
                                {
                                    title: '规则编号',
                                    dataIndex: 'ruleNo',
                                    key: 'ruleNo'
                                },
                                {
                                    title: '规则名称',
                                    dataIndex: 'ruleName',
                                    key: 'ruleName'
                                },
                                {
                                    title: '法规名称',
                                    dataIndex: 'regulationName',
                                    key: 'regulationName'
                                },
                                {
                                    title: '法规条目',
                                    dataIndex: 'regulationClause',
                                    key: 'regulationClause'
                                },
                              /*  {
                                    title: '文档分类',
                                    dataIndex: 'DocumentClassification',
                                    key: 'DocumentClassification'
                                },*/
                                {
                                    title: '风险等级',
                                    dataIndex: 'riskLevel',
                                    key: 'riskLevel',
                                    render: (riskLevel: string) => <Tag
                                        color={getRiskLevelColor(riskLevel)}>{riskLevel}</Tag>
                                },
                                {
                                    title: '生效状态',
                                    dataIndex: 'status',
                                    key: 'status',
                                    render: (status: number) => <Tag
                                        color={status === 1 ? 'green' : 'gray'}>{status === 1 ? '已生效' : '未生效'}</Tag>
                                },
                                {
                                    title: '生效时间',
                                    dataIndex: 'effectiveTime',
                                    key: 'effectiveTime'
                                },
                                {
                                    title: '操作',
                                    key: 'action',
                                    render: (_: any, record: any) => (
                                        <>
                                            <Button type="link"
                                                    onClick={() => handleEditRegulation(record)}>编辑</Button>
                                            <Button type="link"
                                                    onClick={() => handleDeleteRegulation(record.id)}>删除</Button>
                                        </>
                                    )
                                }
                            ]}
                            pagination={false}
                        />
                    </Spin>
                </div>

                {/* 新增规章制度弹窗 */}
                <Modal
                    title="新增规章制度"
                    open={addModalVisible}
                    onCancel={() => setAddModalVisible(false)}
                    footer={[
                        <Button key="cancel" onClick={() => setAddModalVisible(false)}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" onClick={handleAddSubmit}>
                            提交
                        </Button>
                    ]}
                    width={600}
                >
                    <Form form={addForm} layout="vertical">
                        <Form.Item label="规则编号" name="ruleNo" rules={[{required: true, message: '请输入规则编号'}]}>
                            <Input placeholder="请输入规则编号，如CR01"/>
                        </Form.Item>
                        <Form.Item label="规则名称" name="ruleName"
                                   rules={[{required: true, message: '请输入规则名称'}]}>
                            <Input placeholder="请输入规则名称"/>
                        </Form.Item>
                        <Form.Item label="法规名称" name="regulationName"
                                   rules={[{required: true, message: '请输入法规名称'}]}>
                            <Input placeholder="请输入法规名称"/>
                        </Form.Item>
                        <Form.Item label="法规条目" name="regulationClause"
                                   rules={[{required: true, message: '请输入法规条目'}]}>
                            <Input placeholder="请输入法规条目"/>
                        </Form.Item>
                        <Form.Item label="风险等级" name="riskLevel"
                                   rules={[{required: true, message: '请选择风险等级'}]}>
                            <Select
                                options={[
                                    {value: '高危', label: '高危'},
                                    {value: '中危', label: '中危'},
                                    {value: '低危', label: '低危'}
                                ]}
                            />
                        </Form.Item>
                        <Form.Item label="文档分类" name="DocumentClassification"
                                   rules={[{required: true, message: '请选择文档分类'}]}>
                            <Select
                                options={[
                                    {value: '合同', label: '合同协议'},
                                    {value: '发票', label: '财务文档'},
                                ]}
                            />
                        </Form.Item>
                        <Form.Item label="生效状态" name="status" rules={[{required: true, message: '请选择生效状态'}]}>
                            <Select
                                options={[
                                    {value: 1, label: '已生效'},
                                    {value: 0, label: '未生效'}
                                ]}
                            />
                        </Form.Item>
                        <Form.Item label="生效时间" name="effectiveTime">
                            <DatePicker style={{width: '100%'}} showTime/>
                        </Form.Item>
                    </Form>
                </Modal>

                {/* 编辑规章制度弹窗 */}
                <Modal
                    title="编辑规章制度"
                    open={editModalVisible}
                    onCancel={() => setEditModalVisible(false)}
                    footer={[
                        <Button key="cancel" onClick={() => setEditModalVisible(false)}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" onClick={handleEditSubmit}>
                            提交
                        </Button>
                    ]}
                    width={600}
                >
                    <Form form={editForm} layout="vertical">
                        <Form.Item label="规则编号" name="ruleNo" rules={[{required: true, message: '请输入规则编号'}]}>
                            <Input placeholder="请输入规则编号"/>
                        </Form.Item>
                        <Form.Item label="规则名称" name="ruleName"
                                   rules={[{required: true, message: '请输入规则名称'}]}>
                            <Input placeholder="请输入规则名称"/>
                        </Form.Item>
                        <Form.Item label="法规名称" name="regulationName"
                                   rules={[{required: true, message: '请输入法规名称'}]}>
                            <Input placeholder="请输入法规名称"/>
                        </Form.Item>
                        <Form.Item label="法规条目" name="regulationClause"
                                   rules={[{required: true, message: '请输入法规条目'}]}>
                            <Input placeholder="请输入法规条目"/>
                        </Form.Item>
                        <Form.Item label="风险等级" name="riskLevel"
                                   rules={[{required: true, message: '请选择风险等级'}]}>
                            <Select
                                options={[
                                    {value: '高危', label: '高危'},
                                    {value: '中危', label: '中危'},
                                    {value: '低危', label: '低危'}
                                ]}
                            />
                        </Form.Item>
                        <Form.Item label="生效状态" name="status" rules={[{required: true, message: '请选择生效状态'}]}>
                            <Select
                                options={[
                                    {value: 1, label: '已生效'},
                                    {value: 0, label: '未生效'}
                                ]}
                            />
                        </Form.Item>
                        <Form.Item label="生效时间" name="effectiveTime">
                            <DatePicker style={{width: '100%'}} showTime/>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        );
    };

    return (
        <Layout style={{minHeight: '100vh'}}>
            <Layout.Sider width={200} style={{backgroundColor: '#fff'}}>
                <div className="logo"
                     style={{textAlign: 'center', padding: '16px', fontSize: '18px', fontWeight: 'bold'}}>
                    IN-ORDER
                </div>
                <Menu
                    mode="inline"
                    selectedKeys={[currentPage]}
                    style={{height: '100%', borderRight: 0}}
                    onSelect={({key}) => setCurrentPage(key)}
                    items={[
                        {
                            key: 'dashboard',
                            icon: <FileTextOutlined/>,
                            label: '合同审查',
                        },
                        {
                            key: 'rule',
                            icon: <SettingOutlined/>,
                            label: '风险设置',
                        },
                    ]}
                />
            </Layout.Sider>
            <Layout.Content style={{padding: '24px'}}>
                {currentPage === 'dashboard' && <DashboardPage/>}
                {currentPage === 'detail' && <DetailPage/>}
                {currentPage === 'rule' && <RiskModulePage/>}
                <SubmitReviewModal/>
            </Layout.Content>
        </Layout>
    );
};

export default App;