import React, { useState, useEffect } from 'react';
import { Row, Col, Input, Select, Button, Table, Space } from 'antd';
import { withRouter, RouteComponentProps } from 'react-router-dom'; // 引入 withRouter 和 RouteComponentProps
import {
    getExamPaperAnalysisPageList,
    getIndustryList,
    getPaperAnalysisData, getScoreDistribution
} from 'api/exam-online/index';
import ESBreadcrumbComponent from "./ESBreadcrumbComponent"; // 假设的接口导入

const { Option } = Select;

// 定义表格数据项的类型
export type PaperAnalysisDataItem = {
    key: string;
    paperId: string;
    paperName: string;
    industry: string;
    useCount: number;
    participantCount: number;
    accuracyRate: string;
};

const ExamPaperAnalysisPage: React.FC<RouteComponentProps> = ({history}) => {
    const [paperName, setPaperName] = useState('');
    const [industry, setIndustry] = useState(null);
    const [industryOptions, setIndustryOptions] = useState<{ value: string; label: string }[]>([]);
    const [tableData, setTableData] = useState<PaperAnalysisDataItem[]>([]);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: tableData.length,
    });
    const [totalCount, setTotalCount] = useState(0);
    const [usedCount, setUsedCount] = useState(0);
    const [disabledCount, setDisabledCount] = useState(0);

    useEffect(() => {
        const fetchData = async () => {
            try {
                const industryResponse = await getIndustryList();
                setIndustryOptions(industryResponse.map((item: any) => ({ value: item.industry_id, label: item.industry_name })));

                const paperAnalysisResponse = await getPaperAnalysisData();
                setTotalCount(paperAnalysisResponse.totalCount);
                setUsedCount(paperAnalysisResponse.usedCount);
                setDisabledCount(paperAnalysisResponse.disabledCount);
                handleSearch();
            } catch (error) {
                console.error('数据获取失败:', error);
            }
        };
        fetchData();
    }, []);

    const handleReset = () => {
        setPaperName('');
        setIndustry(null);
        setTableData(tableData);
        setPagination({
            ...pagination,
            current: 1,
        });
    };

    const handleShowScoreDistribution = async (paperId: string) => {
        try {
            history.push({
                pathname: '/exam_paper_analysis_detail',
                state: { paperId: String(paperId) }
            });
        } catch (error) {
            console.error('获取成绩分布数据失败:', error);
        }
    };

    const handleSearch = () => {
        const param = {
            paperName:paperName,
            industry:!industry ? '' : industry
        }
        const fetchData = async () => {
            try {
                const resultData = await getExamPaperAnalysisPageList(param)
                setTableData(resultData);
                setPagination({
                    ...pagination,
                    current: 1,
                    total: resultData.length,
                });
            } catch (error) {
                console.error('数据获取失败:', error);
            }
        };
        fetchData();
    };

    const handleTableChange = (newPagination: any) => {
        setPagination(newPagination);
    };

    const columns: any = [
        {
            title: '序号',
            dataIndex: 'key',
            width: 70,
            align: 'center',
            render: (text: any, record: PaperAnalysisDataItem, index: number) => (pagination.current - 1) * pagination.pageSize + index + 1,
        },
        {
            title: '试卷名称',
            dataIndex: 'paperName',
        },
        {
            title: '监管行业',
            dataIndex: 'industry',
        },
        {
            title: '使用次数',
            dataIndex: 'useCount',
        },
        {
            title: '参与人数',
            dataIndex: 'participantCount',
        },
        {
            title: '准确率',
            dataIndex: 'accuracyRate',
            render: (text:any, record: PaperAnalysisDataItem) =>{
                if(record.accuracyRate){
                    return record.accuracyRate+"%";
                }else{
                    return "";
                }
            }
        },
        {
            title: '查看',
            dataIndex: 'view',
            render: (text:any, record: PaperAnalysisDataItem) => <a onClick={()=>{handleShowScoreDistribution(record.paperId)}}>题目正确率分析</a>,
        },
    ];

    return (
        <div>
            <div className="header-filter">
                <div className="list-filter" style={{ padding: 15}}>
                    <Row gutter={24}>
                        <Col span={8}>
                            <span style={{ marginRight: 8 }}>试卷名称:</span>
                            <Input
                                placeholder="试卷名称"
                                value={paperName}
                                onChange={(e) => setPaperName(e.target.value)}
                                style={{ width: 300 }}
                            />
                        </Col>
                        <Col span={8}>
                            <span style={{ marginRight: 8 }}>监管行业:</span>
                            <Select
                                placeholder="监管行业"
                                value={industry}
                                onChange={(value) => setIndustry(value)}
                                style={{ width: 300 }}
                                allowClear
                            >
                                {industryOptions.map((option) => (
                                    <Option key={option.value} value={option.value}>
                                        {option.label}
                                    </Option>
                                ))}
                            </Select>
                        </Col>
                        <Col span={8}>
                            <Space>
                                <Button onClick={handleReset}>重置</Button>
                                <Button type="primary" onClick={handleSearch}>查询</Button>
                            </Space>
                        </Col>
                    </Row>
                </div>
            </div>
            <Row gutter={24} style={{ marginTop: 40 }}>
                <Col span={8}>
                    <div className="exam-statistic-box">
                        <div className="exam-statistic">
                            <span style={{ color: 'black' }}>总计</span>
                            <span style={{ color: '#86A3E7', margin: 10 }}>{totalCount}</span>
                            <span style={{ color: 'black' }}>套</span>
                        </div>
                    </div>
                </Col>
                <Col span={8}>
                    <div className="exam-statistic-box">
                        <div className="exam-statistic">
                            <span style={{ color: 'black' }}>已使用</span>
                            <span style={{ color: '#86A3E7', margin: 10 }}>{usedCount}</span>
                            <span style={{ color: 'black' }}>套</span>
                        </div>
                    </div>
                </Col>
                <Col span={8}>
                    <div className="exam-statistic-box">
                        <div className="exam-statistic">
                            <span style={{ color: 'black' }}>停用</span>
                            <span style={{ color: '#86A3E7', margin: 10 }}>{disabledCount}</span>
                            <span style={{ color: 'black' }}>套</span>
                        </div>
                    </div>
                </Col>
            </Row>
            {/* 表格 */}
            <div style={{marginTop: 20}}>
                <div style={{fontSize: 'large', fontWeight: 600}}>已使用试卷分析</div>
                <Table
                    columns={columns}
                    dataSource={tableData}
                    pagination={pagination}
                    bordered={true}
                    size={'small'}
                    onChange={handleTableChange}
                />
            </div>
        </div>
    );
};

export default withRouter(ExamPaperAnalysisPage);