
import { useState, useEffect, useRef } from 'react';
import { Space, Select, Button, Spin, Table, Modal,Empty } from 'antd';
import { getKnowledgeRanking, getKnowledgeRankingAnalysis } from '@/apis/exam';
import { getSubjectList } from '@/apis/common';
import SchoolChoice from '@/components/SchoolChoice';
import Echarts from "@/components/Echarts";
import { tableCommonProps } from '@/utils/config.js';
import { downloadTableData } from '@/apis/download';
import { downloadExcelFile } from '@/utils/file';
import navIconSrc from '@/assets/icon/analysis-navigation-icon.png';
import styles from './index.less';

const KnowledgeComparisonAnalysis = (props) => {



    const { examId = '', subtitle = '', examList = [],idx='' ,actionShow = true} = props;
    const [dataSource, setDataSource] = useState([]);
    const [columns, setColumns] = useState([]);
    const [responseData, setResponseData] = useState({});
    const [loading, setLoading] = useState(false);
    const [subjectId, setSubjectId] = useState("");
    const [subjectName, setSubjectName] = useState(null);
    const [schoolIds, setSchoolIds] = useState([]);

    const [visible, setVisible] = useState(false);
    const [modalLoading, setModalLoading] = useState(false);
    const [totalDataSource, setTotalDataSource] = useState([]);
    const [originData, setOriginData] = useState([]);
    const [record, setRecord] = useState({});
    const [title, setTitle] = useState('');


    const [singleSubjectList, setSingleSubjectList] = useState([]);


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

    useEffect(() => {

        if (visible) {
            getKnowledgeRankingAnalysisDetail();
        } else {
            setTotalDataSource([]);
            setModalLoading(false);
            setOriginData([]);
        }

    }, [visible, record?.type, record?.value]);
    useEffect(() => {

        if (!examId || !subjectId) {
            return;
        }
        init();

    }, [examId, schoolIds, subjectId,examList]);


    const init = async () => {
        setLoading(true);
        try {
            const res = await getKnowledgeRanking({
                subjectId: subjectId,
                examIds: [examId, ...examList.map(item => item.id)],
                schools: schoolIds
            });
            if (res.code === 200) {
                setResponseData(res);
                setLoading(false);
                setDataSource(res?.data || []);
                setColumns(() => {
                    return res?.columns?.map(item => {

                        if (item?.label === '题目序号') {
                            return {
                                title: item?.label,
                                dataIndex: item?.prop,
                                align: "center",
                                width: 90
                            }
                        }
                        return {
                            title: item?.label,
                            dataIndex: item?.prop,
                            align: "center",
                            render(value, record) {

                                return record?.[item?.prop]?.map((element,index) => {
                                    return (
                                        <p style={{ cursor: "pointer", color: "#4ABB6A" }} key={index} onClick={() => {
                                            setVisible(true);
                                            setModalLoading(true);
                                            setTitle(`知识点对比情况：${element}`);
                                            setRecord({ ...record, subjectId: subjectId, });
                                        }}>
                                            {element}
                                        </p>
                                )
                                })

                                // return (<span style={{ cursor: "pointer", color: "#4ABB6A" }} onClick={() => {
                                //     setVisible(true);
                                //     setModalLoading(true);
                                //     setTitle(`知识点对比情况：${value?.join('')}`);
                                //     setRecord(record);
                                // }}>
                                //     {value?.join('')}
                                // </span>)
                            }

                        }
                    })
                })
                return;
            }
            setLoading(false);

        } catch (error) {
            setLoading(false);
            console.log(error, 'exam-ranking-error');

        }

    };



    const singleSubjectInit = async () => {
        try {
            const res = await getSubjectList();
            if (res?.code === 200) {
                const element = res?.data?.find(item => item?.cname === '数学');
                setSubjectId(element?.id || '');
                setSubjectName(element?.cname || null);
                setSingleSubjectList(() => {
                    return res?.data?.map(item => {
                        return {
                            label: item?.cname,
                            value: item?.id
                        }
                    })
                })
            }

        } catch (error) {
            console.log(error, 'singleSubjectInit-error');

        }
    };


    const getKnowledgeRankingAnalysisDetail = async () => {



        try {
            const res = await getKnowledgeRankingAnalysis({
                examIds: [examId, ...examList?.filter(item => item?.id !== examId)?.map(item => item?.id)],
                schools: schoolIds,
                subjectId: subjectId,
                type: record.type,
                knowLedge: record?.exam?.[0]

            });
            if (res?.code === 200) {
                setModalLoading(false);
                setOriginData(res?.data);
                const list = res?.data?.map(item => {
                    return {
                        name: item?.name || '',
                        columns: item?.columns?.map(element => {
                            return {
                                title: element?.label,
                                dataIndex: element?.prop,
                                align: "center",
                                sorter: element?.sortable ? (a, b) => a[element?.prop] - b[element?.prop] : false,
                                children: element?.children?.map(child => {
                                    return {
                                        title: child?.label,
                                        dataIndex: child?.prop,
                                        align: "center",
                                        sorter: child?.sortable ? (a, b) => a[child?.prop] - b[child?.prop] : false,
                                    }
                                })
                            }
                        }) || [],
                        data: item?.data || []
                    }
                });
                setTotalDataSource(list || []);
            }

        } catch (error) {
            setModalLoading(false);
            console.log(error, 'getKnowledgeRankingAnalysisDetail-error');

        }

    };

    const handleDownload = async () => {
        try {
            const res = await downloadTableData(responseData);
            if (res?.status === 200) {
                downloadExcelFile(res, `${subtitle}*${subjectName}对比考试知识点分析`);
            }

        } catch (error) {
            console.log(error, 'download-error');

        }
    };


    const handleDownload2 = async (index, name) => {
        try {
            const element = originData?.[index];
            const res = await downloadTableData(element);
            if (res?.status === 200) {
                downloadExcelFile(res, name || 'excel');
            }

        } catch (error) {
            console.log(error, 'download-error');

        }
    };

    return (
        <div>
            <section className={styles.analysis_content_table} id={`operationExport${idx}`}>
                <section className={styles.analysis_content_table_title}>
                    <section className={styles.page_title}>
                        <img src={navIconSrc} className={styles.page_title_img} />
                        <span className={styles.page_title_text}>{subtitle}对比考试知识点分析-表格</span>
                        <Space>
                            <Select
                                placeholder="请选择学科"
                                options={singleSubjectList}
                                value={subjectName}
                                style={{ marginLeft: 20, width: "120px" }}
                                onChange={(value, options) => {
                                    if (!value) {
                                        return;
                                    }
                                    setSubjectName(options?.label);
                                    setSubjectId(value);
                                }}
                            />
                            <SchoolChoice onChange={(value) => {
                                setSchoolIds(value);
                            }} />
                        </Space>
                    </section>
                    {actionShow &&  <Button type='primary' style={{ fontSize: 16 }} onClick={handleDownload}>导出表格</Button>}
                </section>
                <section className={styles.analysis_content_table_content}>
                    <Table
                        {...tableCommonProps}
                        dataSource={dataSource}
                        columns={columns}
                        locale={{ emptyText: loading ? "计算中，请稍后" : "暂无数据" }}
                        loading={{ spinning: loading, tip: "计算中，请稍后" }}
                    >
                    </Table>
                </section>
            </section>



            <Modal
                width={'80vw'}
                title={title}
                open={visible}
                loading={modalLoading}
                styles={{ body: { height: "80vh", overflowY: "scroll" } }}
                onCancel={() => setVisible(false)}
                maskClosable={false}
                onOk={() => {
                    setVisible(false);

                }}
                destroyOnClose
                centered
            >
                {totalDataSource?.length > 0 ? (
                    totalDataSource?.map((item, index) => {
                        if (item.data?.length === 0) {
                            return;
                        }
                        return (
                            <section className={styles.modal_content} key={index}>
                                <span style={{ fontSize: 16, fontWeight: "bold" }}>{item?.name}</span>
                                <section style={{ overflow: "auto" }}>
                                    <Table
                                        bordered={true}
                                        dataSource={item?.data}
                                        columns={item?.columns}
                                        scroll={{ x: 1500 }}
                                        // height={460}
                                        pagination={false}
                                        sticky={true}
                                        rowKey="id"
                                    // expandable={{
                                    //     defaultExpandedRowKeys: [item?.data?.[0]?.id],
                                    // }}
                                    >
                                    </Table>
                                </section>
                                {actionShow && <Button
                                    type="primary"
                                    style={{ marginTop: 16 }}
                                    disabled={!dataSource?.length}
                                    onClick={() => handleDownload2(index, item?.name)}
                                >
                                    导出表格
                                </Button>}
                            </section>
                        )
                    })
                ) : <Empty />}


            </Modal>
        </div>
    )
};


export default KnowledgeComparisonAnalysis;