import { useRef, useEffect, useState, useMemo } from 'react';
import * as echarts from 'echarts';
import { Space, Tag, Button, Image, Modal, Table, Empty, Select } from 'antd';
import Flex from "@/components/Flex";
import ScreenPage from "@/components/ScreenPage";
import StudentModal from "@/pages/report/components/StudentModal";
import { studentData, studentCol } from "@/pages/mock/tableData";
import { getKnowledgeRanking, getKnowledgeRankingAnalysis } from '@/apis/exam';
import { getExam, getSubjectList } from '@/apis/common';
import upSrc from "@/assets/image/up.png";
import downSrc from "@/assets/image/down.png";
import Common from "@/utils/Common";
import styles from './index.less';
import { downloadTableData } from '@/apis/download';
import { downloadExcelFile } from '@/utils/file';

const RankingComparisonPage = () => {


    const [visibleModal, setVisibleModal] = useState(false);

    const [isShow1, setIsShow1] = useState(false);
    const [isShow2, setIsShow2] = useState(false);
    const [open, setOpen] = useState(1);
    const [isDx, setisDx] = useState(true);
    const [expandedRowKeys, setExpandedRowKeys] = useState([]);



    const handleExpand = (expanded, record) => {
        if (expanded) {
            setExpandedRowKeys([...expandedRowKeys, record.no]);
        } else {
            setExpandedRowKeys(expandedRowKeys.filter((k) => k !== record.no));
        }
    };


    const [subtitle, setSubtitle] = useState('');
    const [params, setParams] = useState({});
    const [dataSource, setDataSource] = useState([]);
    const [columns, setColumns] = useState([]);
    const [loading, setLoading] = useState(false);
    const [examList, setExamList] = useState([]);

    const [visible, setVisible] = useState(false);
    const [title, setTitle] = useState('');

    const [modalLoading, setModalLoading] = useState(false);



    const [record, setRecord] = useState({});

    const [totalDataSource, setTotalDataSource] = useState([]);

    const [subjectId, setSubjectId] = useState('');
    const [singleSubjectList, setSingleSubjectList] = useState([]);
    const [selectValue, setSelectValue] = useState(null);
    const [responseData, setResponseData] = useState({});

    const [originData, setOriginData] = useState([]);



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

    useEffect(() => {

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

    }, [visible, record?.type, record?.value]);


    useEffect(() => {
        if (!examList?.length > 0) {
            return;
        }
        init();

    }, [params?.examId, params?.schools, examList, subjectId]);




    const getKnowledgeRankingAnalysisDetail = async () => {



        try {
            const res = await getKnowledgeRankingAnalysis({
                examIds: [...examList?.filter(item => item?.id !== params?.examId)?.map(item => item?.id)],
                schools: params?.schools,
                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 init = async () => {
        setLoading(true);
        try {
            const res = await getKnowledgeRanking({
                ...params,
                subjectId,
                examIds: examList.map(item => item.id),
            });
            if (res.code === 200) {
                setLoading(false);
                setResponseData(res);
                setDataSource(res?.data || []);
                setExpandedRowKeys([res?.data?.[0]?.id]);
                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 === '数学');
                console.log(element,'element');
                
                setSubjectId(element?.id);
                setSelectValue(element?.cname);
                setSingleSubjectList(() => {
                    return res?.data?.map(item => {
                        return {
                            label: item?.cname,
                            value: item?.id
                        }
                    })
                })
            }

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

        }
    };

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

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

        }
    };

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

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

        }
    };

    return (
        <div className={styles.ranking}>
            {/* <ScreenPage
                isShow={open == 2 ? isShow1 : isShow2}
                isSingle={isDx}
                isShowSubject={false}
                isTeacher={true}
                onChange={(e) => {
                    setParams({
                        examId: e?.examId,
                        schools: e?.currentSchool?.[0]?.schoolList?.map(item => item?.id) || e?.currentSchool?.map(item => item?.id),
                        subjectId: e?.currentDiscipline?.[0]?.id || '',
                    });

                    if (open === 1 || open === 2) {
                        setSubtitle([e?.currentGrade?.[0]?.name, e?.currentSemester?.[0]?.name, e?.currentExamination?.[0]?.name].filter(item => !!item).join("*"));

                        return;
                    }

                    if (open === 3) {
                        const term = e?.currentGrade?.map(item => item?.name);
                        const semester = e?.currentSemester?.map(item => item?.name);
                        const examName = e?.currentExamination?.map(item => item?.name);
                        getExam({
                            term,
                            semester,
                            examName,
                        }).then(res => {
                            if (res.code === 200) {
                                setExamList(res.data || []);
                            }

                        }).catch(error => {
                            console.log(error, 'get-exam-error');

                        })
                    }
                }}
                saveshow={(e) => {
                    setisDx(true);
                    open == 2 ? setIsShow1(e) : setIsShow2(e);
                }}
            /> */}

            {/* <div style={{ display: (isShow1 && !isShow2) ? 'block' : 'none' }}>
                <ScreenPage
                    isShow={isShow1}
                    isSingle={true}
                    isShowSubject={false}
                    isTeacher={true}
                    onChange={(e) => {
                        setSubtitle([e?.currentGrade?.[0]?.name, e?.currentSemester?.[0]?.name, e?.currentExamination?.[0]?.name].filter(item => !!item).join("*"));
                        setParams({
                            examId: e?.examId,
                            schools: e?.currentSchool?.[0]?.schoolList?.map(item => item?.id) || e?.currentSchool?.map(item => item?.id),
                            subjectId: e?.currentDiscipline?.[0]?.id || '',
                        });
                    }}
                    saveshow={(e) => {
                        setIsShow1(e);
                    }}
                />
            </div> */}

            <div style={{ display: (isShow2 && !isShow1) ? 'block' : 'none' }}>
                <ScreenPage
                    isShow={isShow2}
                    isSingle={false}
                    isShowSubject={false}
                    isTeacher={true}
                    onChange={(e) => {
                        setParams({
                            schools: e?.currentSchool?.[0]?.schoolList?.map(item => item?.id) || e?.currentSchool?.map(item => item?.id),
                        });
                        const term = e?.currentGrade?.map(item => item?.name);
                        const semester = e?.currentSemester?.map(item => item?.name);
                        const examName = e?.currentExamination?.map(item => item?.name);
                        getExam({
                            term,
                            semester,
                            examName,
                        }).then(res => {
                            if (res.code === 200) {
                                setExamList(res.data || []);
                            }

                        }).catch(error => {
                            console.log(error, 'get-exam-error');

                        })
                    }}
                    saveshow={(e) => {
                        setIsShow2(e);
                    }}
                />
            </div>

            <section className={styles.ranking_table} style={{ marginTop: 16 }} >
                {/* <Card hoverable title='对比考试排名情况分析'> */}
                <span style={{ fontSize: 16, fontWeight: "bold" }}>对比考试知识点分析</span>
                <Select
                    placeholder="请选择学科"
                    options={singleSubjectList}
                    style={{ marginLeft: 20, width: "120px" }}
                    value={selectValue}
                    onChange={(value, option) => {
                        if (!value) {
                            return;
                        }
                        setSelectValue(option?.label);
                        setSubjectId(value);
                    }}
                />
                {/* <Flex
                    style={{
                        display: "flex",
                        alignItems: "center",
                        margin: "5px 0",
                        gap: 12,
                    }}
                    alignItems="center"
                >
                    <Flex alignItems="center">
                        <Flex
                            style={{
                                display: "flex",
                                alignItems: "center",
                                color: "#8a8a8a",
                            }}
                        >
                            {" "}
                            当前考试 : &nbsp;
                            <h3
                                style={{
                                    color: "black",
                                }}
                            >
                                {subtitle}
                            </h3>
                        </Flex>
                    </Flex>

                    <Flex
                        style={{
                            padding: "4px 8px",
                            border: "1px solid #666",
                            borderRadius: 5,
                            cursor: "pointer",
                            marginLeft: 10,
                        }}
                        alignItems="center"
                        onClick={() => {
                            setIsShow1(!isShow1);
                            setIsShow2(false);
                        }}
                    >
                        选择考试和学校
                        <img
                            src={isShow1 ? upSrc : downSrc}
                            width={14}
                            height={12}
                            style={{ marginLeft: 5 }}
                        />
                    </Flex>
                </Flex> */}
                {/* <Flex
                    style={{
                        width: "100%",
                        display: "flex",
                        alignItems: "center",
                        margin: "5px 0",
                    }}
                    alignItems="center"
                >
                    <Flex alignItems="center">
                        <Flex alignItems="center"
                            style={{
                                width: "100%",
                                display: "flex",
                                alignItems: "center",
                                color: "#8a8a8a",
                            }}
                        >
                            对比考试 : &nbsp;
                            <Flex wrap="wrap">
                                {examList?.map((item) => {
                                    return (
                                        <Tag
                                            key={item.id}
                                            // closeIcon
                                            // onClose={(e) => {
                                            //     e.preventDefault();
                                            //     setExamList((prev) => {
                                            //         return prev.filter((i) => i?.id !== item?.id)
                                            //     });
                                            // }}
                                            style={{
                                                color: "black",
                                                fontWeight: "bold",
                                                fontSize: 14
                                            }}
                                        >
                                            {`${item?.term}*${item?.semester}*${item?.examName}`}
                                        </Tag>
                                    );
                                })}
                            </Flex>
                        </Flex>
                    </Flex>

                    <Flex
                        style={{
                            padding: "4px 8px",
                            border: "1px solid #666",
                            borderRadius: 5,
                            cursor: "pointer",
                            marginLeft: 10,
                        }}
                        alignItems="center"
                        onClick={() => {
                            setOpen(3);
                            setisDx(false);
                            setIsShow2(!isShow2);
                        }}
                    >
                        选择考试和学校
                        <img
                            src={isShow2 ? upSrc : downSrc}
                            width={14}
                            height={12}
                            style={{ marginLeft: 5 }}
                        />
                    </Flex>
                </Flex> */}
                <section className={styles.select}>
                    <div className={styles.select_title}>对比考试: &nbsp;</div>
                    <section className={styles.select_content}>
                        {examList?.map((item) => {
                            return (
                                <Tag
                                    key={item.id}
                                    // onClose={(e) => {
                                    //     e.preventDefault();
                                    //     setExamList((prev) => {
                                    //         return prev.filter((i) => i?.id !== item?.id)
                                    //     });
                                    // }}
                                    // closeIcon
                                    style={{
                                        color: "black",
                                        fontWeight: "bold",
                                        fontSize: 14,
                                        marginTop: 4,
                                        height: 24
                                    }}
                                >
                                    {`${item?.term}*${item?.semester}*${item?.examName}`}
                                </Tag>
                            );
                        })}
                        <div
                            className={styles.select_action}
                            onClick={() => {
                                setIsShow2(!isShow2);
                                setIsShow1(false);
                            }}
                        >
                            选择考试和学校
                            <img
                                src={isShow2 ? upSrc : downSrc}
                                width={14}
                                height={12}
                                style={{ marginLeft: 5 }}
                            />

                        </div>
                    </section>
                </section>

                <section style={{marginTop: 16 }}>
                    <Table
                        bordered={true}
                        dataSource={dataSource}
                        columns={columns}
                        locale={{ emptyText: loading ? "计算中，请稍后" : "暂无数据" }}
                        loading={{ spinning: loading, tip: "计算中，请稍后" }}
                        scroll={{ x: 1400,y: 340 }}
                        style={{maxHeight: 460}}
                        pagination={false}
                        sticky={true}
                        rowKey="no"
                        expandable={{
                            expandedRowKeys,
                            onExpand: handleExpand,
                        }}
                    >

                    </Table>
                </section>
                {/* </Card> */}
                <Button
                    type="primary"
                    style={{ marginTop:8 }}
                    disabled={!dataSource?.length}
                    onClick={handleDownload}
                >
                    导出表格
                </Button>
            </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>
                                <Button
                                    type="primary"
                                    style={{ marginTop: 16 }}
                                    disabled={!dataSource?.length}
                                    onClick={()=>{handleDownload1(index,item?.name)}}
                                >
                                    导出表格
                                </Button>
                            </section>
                        )
                    })
                ) : <Empty />}


            </Modal>
        </div>
    )
};

export default RankingComparisonPage;