import { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { Modal, Table, Button, Tag, Select, Spin,Space } from 'antd';
import { SyncOutlined} from '@ant-design/icons';
import ScreenPage from "@/components/ScreenPage";
import Echarts from "@/components/Echarts";
import Common from "@/utils/Common";
import Flex from "@/components/Flex";
import upSrc from "@/assets/image/up.png";
import downSrc from "@/assets/image/down.png";
import { getStudentGroup, getStudentKnowledge, getStudentHistory, getStudentBook, getStudentTopic } from '@/apis/leader';
import { getTeacherRateSort } from '@/apis/rqg';
import { getExam, getSubjectList } from '@/apis/common';
import { downloadTableData } from '@/apis/download';
import { downloadExcelFile } from '@/utils/file';

const StudentGroup = (props, ref) => {

    const { params = {}, title = '' } = props;
    

    const [open, setOpen] = useState(false);

    const [loading, setLoading] = useState(false);

    const [dataSource, setDataSource] = useState([]);

    const [columns, setColumns] = useState([]);

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

    const [loading2, setLoading2] = useState(false);

    const [title2, setTitle2] = useState('');

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

    


    const [isShow1, setIsShow1] = useState(false);
    const [tableIsShow1, setTableIsShow1] = useState(false);
    const [subtitle1, setSubtitle1] = useState('');
    const [params1, setParams1] = useState({});
    const [dataSource1, setDataSource1] = useState([]);
    const [columns1, setColumns1] = useState([]);
    const [loading3, setLoading3] = useState(false);
    const [echartData1, setEchartData1] = useState({});
    const [lengButton1, setLengButton1] = useState([]);
    const [examList, setExamList] = useState([]);



    const [isShow2, setIsShow2] = useState(false);
    const [tableIsShow2, setTableIsShow2] = useState(false);
    const [subtitle2, setSubtitle2] = useState('');
    const [params2, setParams2] = useState({});
    const [dataSource2, setDataSource2] = useState([]);
    const [columns2, setColumns2] = useState([]);
    const [loading4, setLoading4] = useState(false);
    const [echartData2, setEchartData2] = useState({});
    const [lengButton2, setLengButton2] = useState([]);



    const [isShow3, setIsShow3] = useState(false);
    const [tableIsShow3, setTableIsShow3] = useState(false);
    const [subtitle3, setSubtitle3] = useState('');
    const [params3, setParams3] = useState({});
    const [dataSource3, setDataSource3] = useState([]);
    const [columns3, setColumns3] = useState([]);
    const [loading5, setLoading5] = useState(false);
    const [echartData3, setEchartData3] = useState({});
    const [lengButton3, setLengButton3] = useState([]);


    const [isShow4, setIsShow4] = useState(false);
    const [tableIsShow4, setTableIsShow4] = useState(false);
    const [subtitle4, setSubtitle4] = useState('');
    const [params4, setParams4] = useState({});
    const [dataSource4, setDataSource4] = useState([]);
    const [columns4, setColumns4] = useState([]);
    const [loading6, setLoading6] = useState(false);
    const [echartData4, setEchartData4] = useState({});
    const [lengButton4, setLengButton4] = useState([]);

    const [subjectSelect, setSubjectSelect] = useState([]);

    const [selectValue, setSelectValue] = useState(null);

    const [echartObj, setEchartObj] = useState({});

    const [subjectId1, setSubjectId1] = useState('');

    const [subjectValue1, setSubjectValue1] = useState(null);

    const [subjectId2, setSubjectId2] = useState('');

    const [subjectValue2, setSubjectValue2] = useState(null);
    const [singleSubjectList, setSingleSubjectList] = useState([]);

    const [echartData5, setEchartData5] = useState({});
    const [lengButton5, setLengButton5] = useState([]);


    const [combineSubjectList, setCombineSubjectList] = useState([]);
    const [selectCombineSubject, setSelectCombineSubject] = useState([]);
    const [soleSubjectList, setSoleSubjectList] = useState([]);
    const [selectSoleSubject, setSelectSoleSubject] = useState([]);

    const [combineSubjectSortList, setCombineSubjectSortList] = useState([]);
    const [selectCombineSubjectSort, setSelectCombineSubjectSort] = useState([]);
    const [soleSubjectSortList, setSoleSubjectSortList] = useState([]);
    const [selectSoleSubjectSort, setSelectSoleSubjectSort] = useState([]);




    // 处理表格导出数据

    const [responseData1, setResponseData1] = useState({});
    const [responseData2, setResponseData2] = useState({});
    const [responseData3, setResponseData3] = useState({});
    const [responseData4, setResponseData4] = useState({});
    const [responseData5, setResponseData5] = useState({});


    //知识点关联弹窗

    const [knowledgeModalVisible, setKnowledgeModalVisible] = useState(false);
    const [knowledgeModalLoading, setKnowledgeModalLoading] = useState(false);
    const [knowledgeRecord, setKnowledgeRecord] = useState({});
    const [cityCount, setCityCount] = useState(0);
    const [schoolCount, setSchoolCount] = useState(0);

    const [citySortList, setCitySortList] = useState([]);
    const [schoolSortList, setSchoolSortList] = useState([]);

    const [citySpinning, setCitySpinning] = useState(false);
    const [schoolSpinning, setSchoolSpinning] = useState(false);


    useEffect(() => {

        const list1 = [...selectCombineSubject, ...selectSoleSubject];
        let list2 = []
        if (Object.values(echartObj).length > 0) {
            list2 = [...echartObj?.totalScore, ...echartObj?.subjectScore];
            const list1Set = new Set(list1);

            const result = list2.filter(item => list1Set.has(item?.lineName));

            setLengButton1(list1);

            setEchartData1(() => {
                return {
                    xAxis: {
                        name: "",
                        type: "category",
                        axisTick: { show: false },
                        data: result?.[0]?.xdata,
                    },
                    yAxis: {
                        name: "",
                    },
                    tooltip: {
                        show: true,
                    },
                    yChartData: result?.map(item => {
                        return {
                            name: item?.lineName,
                            data: item?.data
                        }
                    })
                }
            });
        }

    }, [selectCombineSubject, selectSoleSubject]);


    useEffect(() => {

        const list1 = [...selectCombineSubjectSort, ...selectSoleSubjectSort];
        let list2 = []
        if (Object.values(echartObj).length > 0) {
            list2 = [...echartObj?.totalSort, ...echartObj?.subjectSort];
            const list1Set = new Set(list1);

            const result = list2.filter(item => list1Set.has(item?.lineName));

            setLengButton5(list1);

            setEchartData5(() => {
                return {
                    xAxis: {
                        name: "",
                        type: "category",
                        axisTick: { show: false },
                        data: result?.[0]?.xdata,
                        position: 'top',
                    },
                    yAxis: {
                        name: "",
                        inverse: true,
                    },
                    tooltip: {
                        show: true,
                    },
                    yChartData: result?.map(item => {
                        return {
                            name: item?.lineName,
                            data: item?.data
                        }
                    })
                }
            });
        }

    }, [selectCombineSubjectSort, selectSoleSubjectSort]);


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


    useEffect(() => {
        if (!Object.values(params).length > 0) {
            return;
        }
        init();
    }, [params?.examId, params?.students]);


    useEffect(() => {
        if (!Object.values(params1).length > 0 || !record?.studentId || !examList.length) {
            return;
        }
        historyInit();
    }, [params1?.examId, params1?.subjectId, record?.studentId, examList]);

    useEffect(() => {
        if (!Object.values(params4).length > 0 || !record?.studentId || !subjectId2) {
            return;
        }
        knowledgeInit();
    }, [params4?.examId, subjectId2, record?.studentId]);

    useEffect(() => {
        if (!Object.values(params2).length > 0 || !record?.studentId) {
            return;
        }
        bookInit();
    }, [params2?.examId, record?.studentId]);

    useEffect(() => {
        if (!Object.values(params3).length > 0 || !record?.studentId || !subjectId1) {
            return;
        }

        topicInit();

    }, [params3?.examId, subjectId1, record?.studentId]);

    useEffect(() => {
        if (!visible) {
            setExamList([]);
            setSelectCombineSubject([]);
            setSelectSoleSubject([]);
            setSelectCombineSubjectSort([]);
            setSelectSoleSubjectSort([]);
        }
    }, [visible]);
    useImperativeHandle(ref, () => ({
        openModal,
        closeModal
    }));

    const init = async () => {
        setLoading(true);
        try {
            const res = await getStudentGroup({
                examId: params?.examId,
                students: params?.students
            });
            if (res.code === 200) {
                setLoading(false);
                setResponseData5(res);
                setDataSource(res?.data || []);
                setColumns(() => {

                    return res?.columns?.map(item => {
                        if (item?.label === '学生姓名') {

                            return {
                                width: 120,
                                title: item?.label,
                                dataIndex: item?.prop,
                                align: "center",
                                render(text, record) {
                                    return (<Button type="link" onClick={() => handleOpenStudentGrowing(record)} style={{ color: '#4ABB6A' }}>{text}</Button>)
                                }
                            }
                        }

                        return {
                            width: 130,
                            title: item?.label,
                            dataIndex: item?.prop,
                            align: "center",
                            sorter: item?.sortable ? (a, b) => a[element?.prop] - b[element?.prop] : false,
                            children: item?.children?.map(element => {
                                return {
                                    width: 90,
                                    title: element?.label,
                                    dataIndex: element?.prop,
                                    align: "center",
                                    sorter: element?.sortable ? (a, b) => a[element?.prop] - b[element?.prop] : false
                                }
                            })
                        }
                    });
                });
            }
            setLoading(false);
        } catch (error) {
            setLoading(false);
            console.log(error, 'get-student-group-error');

        }
    };

    const historyInit = async () => {
        try {


            setLoading3(true);
            const res = await getStudentHistory({
                // ...params1,
                examId: params?.examId,
                examIds: examList.map(item => item.id),

                studentId: record?.studentId
            });

            if (res.code === 200) {
                setLoading3(false);
                setResponseData1(res);
                setDataSource1(res?.data || []);
                setColumns1(() => {
                    return res?.columns?.map(item => {
                        return {
                            title: item?.label,
                            dataIndex: item?.prop,
                            align: "center",
                            width: 300,
                            children: item?.children?.map(element => {
                                return {
                                    title: element?.label,
                                    dataIndex: element?.prop,
                                    align: "center",
                                    width: 200,
                                    sorter: element?.sortable ? (a, b) => a[element?.prop] - b[element?.prop] : false,
                                }
                            })
                        }
                    });
                });
                console.log(res, '学情追踪结果1213');
                if (!res?.columnDiagramResult) {
                    setEchartObj({});
                    setLengButton1([]);
                    setLengButton5([]);
                    setEchartData1([]);
                    setEchartData5([]);
                    return;
                }

                setEchartObj(res?.columnDiagramResult);

                setLengButton1([res?.columnDiagramResult?.totalScore?.[0]?.lineName]);
                setLengButton5([res?.columnDiagramResult?.totalSort?.[0]?.lineName]);

                setSelectCombineSubject([res?.columnDiagramResult?.totalScore?.[0]?.lineName]);
                setCombineSubjectList(res?.columnDiagramResult?.totalScore?.map(item => item?.lineName));
                setSoleSubjectList(res?.columnDiagramResult?.subjectScore?.map(item => item?.lineName));


                setSelectCombineSubjectSort([res?.columnDiagramResult?.totalSort?.[0]?.lineName]);
                setCombineSubjectSortList(res?.columnDiagramResult?.totalSort?.map(item => item?.lineName));
                setSoleSubjectSortList(res?.columnDiagramResult?.subjectSort?.map(item => item?.lineName));

                setEchartData1(() => {
                    return {
                        xAxis: {
                            name: "",
                            type: "category",
                            axisTick: { show: false },
                            data: res?.columnDiagramResult?.totalScore?.[0]?.xdata,
                        },
                        yAxis: {
                            name: "",
                        },
                        tooltip: {
                            show: true,
                        },
                        yChartData: [{
                            name: res?.columnDiagramResult?.totalScore?.[0]?.lineName,
                            data: res?.columnDiagramResult?.totalScore?.[0]?.data
                        }]
                    }
                });
                setEchartData5(() => {
                    return {
                        xAxis: {
                            name: "",
                            type: "category",
                            axisTick: { show: false },
                            data: res?.columnDiagramResult?.totalSort?.[0]?.xdata,
                            position: 'top',
                        },
                        yAxis: {
                            name: "",
                            inverse: true,
                        },
                        tooltip: {
                            show: true,
                        },
                        yChartData: [{
                            name: res?.columnDiagramResult?.totalSort?.[0]?.lineName,
                            data: res?.columnDiagramResult?.totalSort?.[0]?.data
                        }]
                    }
                });

                
                // const subjectList = res?.columnDiagramResult?.subjectScore?.map(item => {
                //     return {
                //         label: item?.lineName?.slice(0, -2),
                //         value: item?.lineName?.slice(0, -2)
                //     }
                // });

                // setSubjectSelect(subjectList);
                // setSelectValue(subjectList?.[0]?.value);
                // setEchartObj(res?.columnDiagramResult || {});

                // setLengButton1([`${subjectList?.[0]?.value}分数`, `${subjectList?.[0]?.value}排名`, `${res?.columnDiagramResult?.totalScore?.[0]?.lineName}`, `${res?.columnDiagramResult?.totalSort?.[0]?.lineName}`]);

                // const currentSubjectList = res?.columnDiagramResult?.subjectScore?.filter(item => item?.lineName?.includes(subjectList?.[0]?.value));
                // const currentSubjectList2 = res?.columnDiagramResult?.subjectSort?.filter(item => item?.lineName?.includes(subjectList?.[0]?.value));

                // const echartList = [currentSubjectList, currentSubjectList2, res?.columnDiagramResult?.totalScore, res?.columnDiagramResult?.totalSort];
                // setEchartData1(() => {
                //     return {
                //         xAxis: {
                //             name: "",
                //             type: "category",
                //             axisTick: { show: false },
                //             data: res?.columnDiagramResult?.totalScore?.[0]?.xdata,
                //         },
                //         yAxis: {
                //             name: "",
                //         },
                //         tooltip: {
                //             show: true,
                //         },
                //         yChartData: echartList?.map(item => {
                //             return {
                //                 name: item?.[0]?.lineName,
                //                 data: item?.[0]?.data
                //             }
                //         })
                //     }
                // })
            }
            setLoading3(false);
        } catch (error) {
            setLoading3(false);
            console.log(error, 'error');

        }
    };

    const bookInit = async () => {
        try {
            setLoading4(true);
            const res = await getStudentBook({
                examId: params2?.examId,
                studentId: record?.studentId
            });


            if (res?.code === 200) {
                setLoading4(false);
                setResponseData2(res);
                setDataSource2(res?.data || []);
                setColumns2(() => {
                    return res?.columns?.map(item => {
                        return {
                            title: item?.label,
                            dataIndex: item?.prop,
                            align: "center",
                            sorter: item?.sortable ? (a, b) => a[item?.prop] - b[item?.prop] : false
                        }
                    })
                })

            };
            setLoading4(false);
        } catch (error) {
            setLoading4(false);
            console.log(error, 'bookInit-error');

        }
    }

    const topicInit = async () => {
        try {

            setLoading5(true);
            const res = await getStudentTopic({
                ...params3,
                studentId: record?.studentId,
                subjectId: subjectId1

            });
            if (res.code === 200) {
                setLoading5(false);
                setResponseData3(res);
                setDataSource3(res?.data || []);
                setColumns3(() => {
                    return res?.columns?.map(item => {
                        return {
                            title: item?.label,
                            dataIndex: item?.prop,
                            align: "center",
                        }
                    });
                });
                if (!res.columnDiagramResult || !res?.columnDiagramResult?.difficult?.[0]?.data.length > 0 || !res?.columnDiagramResult?.rate?.[0]?.data?.length > 0) {
                    setEchartData3({});
                    setLengButton3([]);
                    return;
                }

                setLengButton3(res?.columnDiagramResult?.difficult?.map(item => item?.lineName));

                setEchartData3(() => {
                    return {
                        xAxis: {
                            name: "",
                            type: "category",
                            axisTick: { show: false },
                            data: res?.columnDiagramResult?.difficult?.[0]?.xdata,
                        },
                        yAxis: {
                            name: "",
                        },
                        tooltip: {
                            show: true,
                        },
                        yChartData: res?.columnDiagramResult?.difficult?.map(item => {
                            return {
                                name: item?.lineName,
                                data: item?.data
                            }
                        }),
                        radarText: {
                            indicator: res?.columnDiagramResult?.rate?.[0]?.xdata?.map(item => {
                                return {
                                    name: item,
                                    max: 100
                                }
                            }),
                            yChartData: res?.columnDiagramResult?.rate?.map(item => {
                                return {
                                    name: item?.lineName,
                                    data: item?.data
                                }
                            }),
                        }
                    }
                });

            }
            setLoading5(false);
        } catch (error) {
            setLoading5(false);
            console.log(error, 'get-student-question-error');

        }
    }


    const knowledgeInit = async () => {

        try {

            setLoading6(true);
            const res = await getStudentKnowledge({
                ...params4,
                studentId: record?.studentId,
                subjectId: subjectId2

            });
            if (res.code === 200) {
                setLoading6(false);
                setDataSource4(res?.data || []);
                setResponseData4(res);
                setColumns4(() => {
                    
                    return res?.columns?.map(item => {
                        if (item?.label === '知识点') {
                            return {
                                title: item?.label,
                                dataIndex: item?.prop,
                                align: "center",
                                render(_, record) {
                                    return <Button type='link' onClick={() => {
                                        setKnowledgeModalVisible(true);
                                        setKnowledgeRecord(record);
                                    }} style={{ color: '#4ABB6A' }}>{record?.Knowledge}</Button>
                                }
                            }
                        }
                        return {
                            title: item?.label,
                            dataIndex: item?.prop,
                            align: "center",
                        }
                    });
                });
                if (!res.columnDiagramResult || !res?.columnDiagramResult?.difficult?.[0]?.data.length > 0 || !res?.columnDiagramResult?.rate?.[0]?.data?.length > 0) {
                    setEchartData4({});
                    setLengButton4([]);
                    return;
                }

                setLengButton4(res?.columnDiagramResult?.difficult?.map(item => item?.lineName));

                setEchartData4(() => {
                    return {
                        xAxis: {
                            name: "",
                            type: "category",
                            axisTick: { show: false },
                            data: res?.columnDiagramResult?.difficult?.[0]?.xdata,
                        },
                        yAxis: {
                            name: "",
                        },
                        tooltip: {
                            show: true,
                        },
                        yChartData: res?.columnDiagramResult?.difficult?.map(item => {
                            return {
                                name: item?.lineName,
                                data: item?.data
                            }
                        }),
                        radarText: {
                            indicator: res?.columnDiagramResult?.rate?.[0]?.xdata?.map(item => {
                                return {
                                    name: item,
                                    max: 100
                                }
                            }),
                            yChartData: res?.columnDiagramResult?.rate?.map(item => {
                                return {
                                    name: item?.lineName,
                                    data: item?.data
                                }
                            }),
                        }
                    }
                });

            }
            setLoading6(false);
        } catch (error) {
            setLoading6(false);
            console.log(error, 'get-student-knowledge-error');

        }

    };


    const singleSubjectInit = async () => {
        try {
            const res = await getSubjectList();
            if (res?.code === 200) {
                setSubjectId1(res?.data?.[0]?.id);
                setSubjectValue1(res?.data?.[0]?.cname);
                setSubjectId2(res?.data?.[0]?.id);
                setSubjectValue2(res?.data?.[0]?.cname);
                setSingleSubjectList(() => {
                    return res?.data?.map(item => {
                        return {
                            label: item?.cname,
                            value: item?.id
                        }
                    })
                })
            }
        } catch (error) {
            console.log(error, 'singleSubjectInit-error');

        }
    };
    useEffect(()=>{
        if(!cityCount){
            return;
        }
        loaderCityTeacherSort();
    },[cityCount]);
    useEffect(()=>{
        if(!schoolCount){
            return;
        }
        loaderSchoolTeacherSort();
    },[schoolCount]);

    useEffect(() => {
        if (knowledgeModalVisible) {
            loadTeacherSort();
        }
    }, [knowledgeModalVisible,subjectId2,knowledgeRecord?.id,record?.studentId]);
    const loadTeacherSort = async () => {
        const data = {
            examId: params?.examId,
            studentId: record?.studentId,
            subjectId: subjectId2,
            rqgId: knowledgeRecord?.id,
            type: "city",
            length: 3,
        };

        try {
            setKnowledgeModalLoading(true);
            const res1 = await getTeacherRateSort({ ...data, pageNum: cityCount });
            const res2 = await getTeacherRateSort({ ...data, type: "school", pageNum: schoolCount });
            setKnowledgeModalLoading(false);
            setCitySortList(res1?.data);
            setSchoolSortList(res2?.data);

        } catch (error) {
            setKnowledgeModalLoading(false);
            console.log(error, 'loadTeacherSort-error');

        }
    };

    const loaderCityTeacherSort =  async() => {
        try {
            setCitySpinning(true);
            const data = {
                examId: params?.examId,
                studentId: record?.studentId,
                subjectId: subjectId2,
                rqgId: knowledgeRecord?.id,
                type: "city",
                length: 3,
                pageNum:cityCount
            };
            const res = await getTeacherRateSort(data);
            setCitySpinning(false);
            setCitySortList(res?.data);
        } catch (error) {
            setCitySpinning(false);
            console.log(error,'loaderCityTeacherSort-error');
            
        }
    };
    const loaderSchoolTeacherSort =  async() => {
        try {
            setSchoolSpinning(true);
            const data = {
                examId: params?.examId,
                studentId: record?.studentId,
                subjectId: subjectId2,
                rqgId: knowledgeRecord?.id,
                type: "school",
                length: 3,
                pageNum:schoolCount
            };
            const res = await getTeacherRateSort(data);
            setSchoolSpinning(false);
            setSchoolSortList(res?.data);
        } catch (error) {
            setSchoolSpinning(false);
            console.log(error,'loaderCityTeacherSort-error');
            
        }
    };
    const openModal = () => {
        setOpen(true);
    };

    const closeModal = () => {
        setOpen(false);
    };

    const handleOpenStudentGrowing = (record) => {
        
        setRecord(record);
        setTitle2(`学生成长性：${record?.school}*${record?.name}`);
        setVisible(true);

    };

    const tableCommonProps = {
        style: { height: 460},
        rowKey: "id",
        scroll: { x: 1500,y:340 },
        sticky: true,
        pagination: false,
    };

    const handleCombineScoreSelect = (tag) => {
        if (selectCombineSubject.includes(tag)) {
            // 如果 Tag 已经选中，则移除
            setSelectCombineSubject((prev) => {
                if (prev.length === 1) {
                    return prev;
                }
                return selectCombineSubject.filter((item) => item !== tag)
            });

        } else {
            // 如果 Tag 未选中，则添加
            setSelectCombineSubject([...selectCombineSubject, tag]);
        }
    };

    const handleSoleScoreSelect = (tag) => {
        if (selectSoleSubject.includes(tag)) {
            setSelectSoleSubject(() => {
                return selectSoleSubject.filter((item) => item !== tag)
            });
        } else {
            setSelectSoleSubject([...selectSoleSubject, tag]);
        }

    };
    const handleCombineSortSelect = (tag) => {
        if (selectCombineSubjectSort.includes(tag)) {
            // 如果 Tag 已经选中，则移除
            setSelectCombineSubjectSort((prev) => {
                if (prev.length === 1) {
                    return prev;
                }
                return selectCombineSubjectSort.filter((item) => item !== tag)
            });

        } else {
            // 如果 Tag 未选中，则添加
            setSelectCombineSubjectSort([...selectCombineSubjectSort, tag]);
        }
    };

    const handleSoleSortSelect = (tag) => {
        if (selectSoleSubjectSort.includes(tag)) {
            setSelectSoleSubjectSort(() => {
                return selectSoleSubjectSort.filter((item) => item !== tag)
            });
        } else {
            setSelectSoleSubjectSort([...selectSoleSubjectSort, tag]);
        }

    };



    const handleDownload1 = async () => {
        try {
            const res = await downloadTableData(responseData1);
            if (res?.status === 200) {
                downloadExcelFile(res, `${record?.school}*${record?.name}*学情追踪`);
            }

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

        }
    };

    const handleDownload2 = async () => {
        try {
            const res = await downloadTableData(responseData2);
            if (res?.status === 200) {
                downloadExcelFile(res, `${record?.school}*${record?.name}*学生成绩册`);
            }

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

        }
    };

    const handleDownload3 = async () => {
        try {
            const res = await downloadTableData(responseData3);
            if (res?.status === 200) {
                downloadExcelFile(res, `${record?.school}*${record?.name}*${subjectValue1}各小题情况`);
            }

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

        }
    };

    const handleDownload4 = async () => {
        try {
            const res = await downloadTableData(responseData4);
            if (res?.status === 200) {
                downloadExcelFile(res, `${record?.school}*${record?.name}*${subjectValue2}知识点情况`);
            }

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

        }
    };

    const handleDownload5 = async () => {
        try {
            const res = await downloadTableData(responseData5);
            if (res?.status === 200) {
                downloadExcelFile(res, `${title || '学生群体'}`);
            }

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

        }
    };

    return (
        <>
            <Modal
                title={title || '学生群体'}
                width={1800}
                zIndex={99}
                styles={{ body: { height: "80vh", overflow: "auto" } }}
                open={open}
                loading={loading}
                onCancel={() => setOpen(false)}
                footer={<Space>
                    <Button type="primary" onClick={handleDownload5}>导出表格</Button>
                    <Button type="primary" onClick={()=>setOpen(false)}>确定</Button>
                </Space>}
                centered
                destroyOnClose
                maskClosable={false}
            >

                <Table
                    bordered={true}
                    dataSource={dataSource}
                    columns={columns}
                    sticky={true}
                    rowKey={(record) => record?.studentId}
                    pagination={false}
                    scroll={{ x: 1200 }}


                >

                </Table>
            </Modal>


            <Modal
                title={title2 || '学生成长性'}
                width={'96vw'}
                styles={{ body: { height: "80vh", overflowY: "scroll", overflowX: "hidden" } }}
                open={visible}
                loading={loading2}
                onOk={() => setVisible(false)}
                onCancel={() => setVisible(false)}
                centered
                zIndex={199}
                destroyOnClose
                maskClosable={false}
            >
                {/* 学情追踪 */}
                <ScreenPage
                    isShow={isShow1}
                    isSingle={false}
                    isShowSubject={true}
                    isShowSort={false}
                    isShowSchool={false}
                    onChange={(e) => {

                        setParams1({
                            examId: e?.examId,
                            subjectId: e?.currentDiscipline?.[0]?.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) => {
                        setIsShow1(e);
                    }}
                />

                <Flex
                    style={{
                        width: "100%",
                        display: "flex",
                        alignItems: "center",
                        margin: "5px 0",
                    }}
                    justify="space-between"
                    alignItems="center"
                >
                    <Flex style={{ width: "90%" }} alignItems="center">
                        <Flex alignItems="center"
                            style={{
                                width: "100%",
                                display: "flex",
                                alignItems: "center",
                                color: "#8a8a8a",
                            }}
                        >
                            学情追踪 : &nbsp;
                            {/* <Flex style={{ width: "90%" }} 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={() => {
                            setIsShow1(!isShow1);
                        }}
                    >
                        选择考试和学校
                        <img
                            src={isShow1 ? upSrc : downSrc}
                            width={14}
                            height={12}
                            style={{ marginLeft: 5 }}
                        />
                    </Flex> */}
                </Flex>

                {!tableIsShow1 ? (
                    <Table
                        {...tableCommonProps}
                        dataSource={dataSource1}
                        columns={columns1}
                        loading={loading3}
                        rowKey="id"
                    >
                    </Table>
                ) : (
                    <>
                        {/* <Select
                            style={{ width: "120px" }}
                            value={selectValue}
                            placeholder='请选择学科'
                            options={subjectSelect}
                            onChange={(value) => {
                                if (!value) {
                                    return;
                                }
                                setSelectValue(value);
                                setLengButton1([`${value}分数`, `${value}排名`, `${echartObj?.totalScore?.[0]?.lineName}`, `${echartObj?.totalSort?.[0]?.lineName}`]);

                                const currentSubjectList = echartObj?.subjectScore?.filter(item => item?.lineName?.includes(value));
                                const currentSubjectList2 = echartObj?.subjectSort?.filter(item => item?.lineName?.includes(value));

                                const echartList = [currentSubjectList, currentSubjectList2, echartObj?.totalScore, echartObj?.totalSort];
                                setEchartData1(() => {
                                    return {
                                        xAxis: {
                                            name: "",
                                            type: "category",
                                            axisTick: { show: false },
                                            data: echartObj?.totalScore?.[0]?.xdata,
                                        },
                                        yAxis: {
                                            name: "",
                                        },
                                        tooltip: {
                                            show: true,
                                        },
                                        yChartData: echartList?.map(item => {
                                            return {
                                                name: item?.[0]?.lineName,
                                                data: item?.[0]?.data
                                            }
                                        })
                                    }
                                })
                            }}
                        /> */}
                        <Spin spinning={loading3}>
                        <section style={{ marginTop: '8px' }}>
                        <section style={{marginBottom:8}}>
                                历次考试分数折线图：
                        </section>
                        <section style={{ display: 'flex' }}>
                            
                            <section style={{ width: 80 }}>
                                学科组合：
                            </section>
                            <Space wrap style={{ width: 'calc(100% - 80px)' }}>
                                {!!combineSubjectList.length ? (

                                    combineSubjectList.map((item, index) => {
                                        const isSelected = selectCombineSubject?.includes(item);
                                        return (
                                            <Button size="small" type={isSelected ? 'primary' : 'default'} key={index} onClick={() => handleCombineScoreSelect(item)}>{item}</Button>
                                        )
                                    })
                                ) : null}
                            </Space>
                        </section>
                        <section style={{ marginTop: 8, display: "flex" }}>
                            <section style={{ width: 80 }}>
                                单一学科：
                            </section>
                            <Space wrap style={{ width: 'calc(100% - 80px)' }}>
                                {!!soleSubjectList.length ? (

                                    soleSubjectList.map((item, index) => {
                                        const isSelected = selectSoleSubject?.includes(item);
                                        return (
                                            <Button size="small" type={isSelected ? 'primary' : 'default'} key={index} onClick={() => handleSoleScoreSelect(item)}>{item}</Button>
                                        )
                                    })
                                ) : null}
                            </Space>
                        </section>
                            <Echarts
                                data={echartData1}
                                type={"line"}
                                isNoneTag={true}
                                isShow={false}
                                text={`${record?.school}*${record?.name}学情追踪-历次考试分数折线图`}
                                lengButton={lengButton1}
                                onTableClick={(e) => {
                                    setTableIsShow1(false);
                                }}
                            />
                        </section>
                        <section style={{ marginTop: '8px' }}>
                                <section style={{marginBottom:8}}>
                                    历次考试排名折线图：
                                </section>
                                <section style={{ display: 'flex' }}>
                                    <section style={{ width: 80 }}>
                                        学科组合：
                                    </section>
                                    <Space wrap style={{ width: 'calc(100% - 80px)' }}>
                                        {!!combineSubjectSortList.length ? (

                                            combineSubjectSortList.map((item, index) => {
                                                const isSelected = selectCombineSubjectSort?.includes(item);
                                                return (
                                                    <Button size="small" type={isSelected ? 'primary' : 'default'} key={index} onClick={() => handleCombineSortSelect(item)}>{item}</Button>
                                                )
                                            })
                                        ) : null}
                                    </Space>
                                </section>
                                <section style={{ marginTop: 8, display: "flex" }}>
                                    <section style={{ width: 80 }}>
                                        单一学科：
                                    </section>
                                    <Space wrap style={{ width: 'calc(100% - 80px)' }}>
                                        {!!soleSubjectSortList.length ? (

                                            soleSubjectSortList.map((item, index) => {
                                                const isSelected = selectSoleSubjectSort?.includes(item);
                                                return (
                                                    <Button size="small" type={isSelected ? 'primary' : 'default'} key={index} onClick={() => handleSoleSortSelect(item)}>{item}</Button>
                                                )
                                            })
                                        ) : null}
                                    </Space>
                                </section>

                            <Echarts
                                data={echartData5}
                                type={"line"}
                                isShow={false}
                                isNoneTag={true}
                                text={`${record?.school}*${record?.name}学情追踪-历次考试排名折线图`}
                                lengButton={lengButton5}
                                onTableClick={(e) => {
                                    setTableIsShow1(false);
                                }}
                            />
                        </section>
                        </Spin>
                    </>
                )}
                {!tableIsShow1 && (
                    <Flex style={{ marginTop: 8 }}>
                        <Button
                            type="primary"
                            style={{ marginRight: 10 }}
                            onClick={handleDownload1}
                        >
                            导出表格
                        </Button>
                        <Button
                            type="primary"
                            onClick={() => {
                                //关闭图表
                                setTableIsShow1(true);
                            }}
                        >
                            显示为图表
                        </Button>
                    </Flex>
                )}
                {/* 学情追踪 */}
                {/* 学生成绩册 */}

                <ScreenPage
                    isShow={isShow2}
                    isShowSubject={false}
                    isShowSchool={false}
                    onChange={(e) => {
                        setSubtitle2([e?.currentGrade?.[0]?.name, e?.currentSemester?.[0]?.name, e?.currentExamination?.[0]?.name].filter(item => !!item).join("*"));
                        setParams2({
                            examId: e?.examId,
                            // subjectId: e?.currentDiscipline?.[0]?.id || '',
                        })
                    }}
                    saveshow={(e) => {
                        setIsShow2(e);
                    }}
                />
                <Flex
                    style={{
                        display: "flex",
                        alignItems: "center",
                        margin: "20px 0",
                        gap: 12,
                    }}
                    justify="space-betweens"
                    alignItems="center"
                >
                    <Flex style={{ flex: 1 }} alignItems="center">
                        <Flex
                            style={{
                                display: "flex",
                                alignItems: "center",
                                color: "#8a8a8a",
                            }}
                        >
                            学生成绩册 : &nbsp;
                            <h3
                                style={{
                                    color: "black",
                                }}
                            >
                                {subtitle2}
                            </h3>
                        </Flex>
                    </Flex>
                    <Flex
                        style={{
                            padding: "4px 8px",
                            border: "1px solid #666",
                            borderRadius: 5,
                            cursor: "pointer",
                        }}
                        alignItems="center"
                        onClick={() => {
                            setIsShow2(!isShow2);
                        }}
                    >
                        选择考试
                        <img
                            src={isShow2 ? upSrc : downSrc}
                            width={14}
                            height={12}
                            style={{ marginLeft: 5 }}
                        />
                    </Flex>
                </Flex>

                <Table
                    {...tableCommonProps}
                    dataSource={dataSource2}
                    columns={columns2}
                    loading={loading4}
                    rowKey="id"
                >
                </Table>

                <Flex style={{ marginTop: 8 }}>
                    <Button
                        type="primary"
                        style={{ marginRight: 10 }}
                        onClick={handleDownload2}
                    >
                        导出表格
                    </Button>
                </Flex>
                {/* 学生成绩册 */}
                {/* 学生小题 */}
                <ScreenPage
                    isShow={isShow3}
                    isShowSubject={true}
                    isShowSchool={false}
                    onChange={(e) => {
                        setSubtitle3([e?.currentGrade?.[0]?.name, e?.currentSemester?.[0]?.name, e?.currentExamination?.[0]?.name].filter(item => !!item).join("*"));
                        setParams3({
                            examId: e?.examId,
                            subjectId: e?.currentDiscipline?.[0]?.id || '',
                        })
                    }}
                    saveshow={(e) => {
                        setIsShow3(e);
                    }}
                />
                <Flex
                    style={{
                        display: "flex",
                        alignItems: "center",
                        margin: "20px 0",
                        gap: 12,
                    }}
                    justify="space-betweens"
                    alignItems="center"
                >
                    <Flex style={{ flex: 1 }} alignItems="center">
                        <Flex
                            style={{
                                display: "flex",
                                alignItems: "center",
                                color: "#8a8a8a",
                            }}
                        >
                            各小题情况 : &nbsp;
                            <h3
                                style={{
                                    color: "black",
                                }}
                            >
                                {subtitle3}
                            </h3>
                            <Select
                                placeholder="请选择学科"
                                options={singleSubjectList}
                                style={{ width: "120px", marginLeft: 16 }}
                                value={subjectValue1}
                                allowClear
                                onChange={(value, option) => {
                                    if (!value) {
                                        return;
                                    }
                                    setSubjectValue1(option?.label);
                                    setSubjectId1(value);
                                }}
                            />
                        </Flex>
                    </Flex>
                    <Flex
                        style={{
                            padding: "4px 8px",
                            border: "1px solid #666",
                            borderRadius: 5,
                            cursor: "pointer",
                        }}
                        alignItems="center"
                        onClick={() => {
                            setIsShow3(!isShow3);
                        }}
                    >
                        选择考试
                        <img
                            src={isShow3 ? upSrc : downSrc}
                            width={14}
                            height={12}
                            style={{ marginLeft: 5 }}
                        />
                    </Flex>
                </Flex>


                {!tableIsShow3 ? (
                    <Table
                        {...tableCommonProps}
                        dataSource={dataSource3}
                        columns={columns3}
                        loading={loading5}
                        rowKey="id"
                    >
                    </Table>
                ) : (
                    <>
                        <Spin spinning={loading5}>
                            <Echarts
                                data={echartData3}
                                type={"line"}
                                text={`${record?.school}*${record?.name}*${subjectValue1}*各小题情况-折线图`}
                                lengButton={lengButton3}
                                onTableClick={(e) => {
                                    setTableIsShow3(false);
                                }}
                            />
                            <Echarts
                                data={echartData3}
                                type={"radar"}
                                text={`${record?.school}*${record?.name}${subjectValue1}*各小题情况-雷达图`}
                                lengButton={lengButton3}
                                onTableClick={(e) => {
                                    setTableIsShow3(false);
                                }}
                            />
                        </Spin>

                    </>
                )}
                {!tableIsShow3 && (
                    <Flex style={{ marginTop: 8 }}>
                        <Button
                            type="primary"
                            style={{ marginRight: 10 }}
                            onClick={handleDownload3}
                        >
                            导出表格
                        </Button>
                        <Button
                            type="primary"
                            onClick={() => {
                                //关闭图表
                                setTableIsShow3(true);
                            }}
                        >
                            显示为图表
                        </Button>
                    </Flex>
                )}
                {/* 学生小题 */}


                {/* 学生知识点 */}
                <ScreenPage
                    isShow={isShow4}
                    isShowSubject={true}
                    isShowSchool={false}
                    onChange={(e) => {
                        setSubtitle4([e?.currentGrade?.[0]?.name, e?.currentSemester?.[0]?.name, e?.currentExamination?.[0]?.name].filter(item => !!item).join("*"));
                        setParams4({
                            examId: e?.examId,
                            subjectId: e?.currentDiscipline?.[0]?.id || '',
                        })
                    }}
                    saveshow={(e) => {
                        setIsShow4(e);
                    }}
                />
                <Flex
                    style={{
                        display: "flex",
                        alignItems: "center",
                        margin: "20px 0",
                        gap: 12,
                    }}
                    justify="space-betweens"
                    alignItems="center"
                >
                    <Flex style={{ flex: 1 }} alignItems="center">
                        <Flex
                            style={{
                                display: "flex",
                                alignItems: "center",
                                color: "#8a8a8a",
                            }}
                        >
                            知识点情况 : &nbsp;
                            <h3
                                style={{
                                    color: "black",
                                }}
                            >
                                {subtitle4}
                            </h3>
                            <Select
                                placeholder="请选择学科"
                                options={singleSubjectList}
                                style={{ width: "120px", marginLeft: 16 }}
                                value={subjectValue2}
                                allowClear
                                onChange={(value, option) => {
                                    if (!value) {
                                        return;
                                    }
                                    setSubjectValue2(option?.label);
                                    setSubjectId2(value);
                                }}
                            />
                        </Flex>
                    </Flex>
                    <Flex
                        style={{
                            padding: "4px 8px",
                            border: "1px solid #666",
                            borderRadius: 5,
                            cursor: "pointer",
                        }}
                        alignItems="center"
                        onClick={() => {
                            setIsShow4(!isShow4);
                        }}
                    >
                        选择考试
                        <img
                            src={isShow4 ? upSrc : downSrc}
                            width={14}
                            height={12}
                            style={{ marginLeft: 5 }}
                        />
                    </Flex>
                </Flex>


                {!tableIsShow4 ? (
                    <Table
                        {...tableCommonProps}
                        dataSource={dataSource4}
                        columns={columns4}
                        loading={loading6}
                        rowKey="id"
                    >
                    </Table>
                ) : (
                    <>
                        <Spin spinning={loading6}>
                            <Echarts
                                data={echartData4}
                                type={"line"}
                                lengButton={lengButton4}
                                text={`${record?.school}*${record?.name}${subjectValue2}*知识点情况-折线图`}
                                onTableClick={(e) => {
                                    setTableIsShow4(false);
                                }}
                            />
                            <Echarts
                                data={echartData4}
                                type={"radar"}
                                lengButton={lengButton4}
                                text={`${record?.school}*${record?.name}${subjectValue2}*知识点情况-雷达图`}
                                onTableClick={(e) => {
                                    setTableIsShow4(false);
                                }}
                            />
                        </Spin>

                    </>
                )}
                {!tableIsShow4 && (
                    <Flex style={{ marginTop: 8 }}>
                        <Button
                            type="primary"
                            style={{ marginRight: 10 }}
                            onClick={handleDownload4}
                        >
                            导出表格
                        </Button>
                        <Button
                            type="primary"
                            onClick={() => {
                                //关闭图表
                                setTableIsShow4(true);
                            }}
                        >
                            显示为图表
                        </Button>
                    </Flex>
                )}
                {/* 学生知识点 */}
            </Modal>
                
            <Modal
                title={`${knowledgeRecord?.Knowledge}优秀教学老师`}
                open={knowledgeModalVisible}
                loading={knowledgeModalLoading}
                onCancel={() => {
                    setKnowledgeModalVisible(false);
                    setCityCount(0);
                    setSchoolCount(0);
                }}
                styles={{ body: { height: 320 } }}
                footer={null}
                maskClosable={false}
                centered
                destroyOnClose
                forceRender
                width={1200}
                zIndex={299}

            >
                <div style={{ height: 280, boxSizing: "border-box", flexDirection: "column", padding: 32, display: "flex", justifyContent: "center", alignItems: "center" }}>
                    <div>
                        <Space size="large">
                            <div style={{ fontSize: 18, fontWeight: "bold" }}>本市：
                                {citySortList?.length > 0 ? (
                                    citySortList?.map((item, index) => {
                                        return (
                                            <span style={{ marginLeft: 16 }} key={index}>
                                                {`${item?.name}(${item?.value}%)`}
                                            </span>
                                        )
                                    })
                                ) : null}
                            </div>
                            <Spin spinning={citySpinning}>
                                <Button type='link' style={{ color: "#4ABB6A", fontSize: 18 }} icon={<SyncOutlined />} onClick={() => {
                                    setCityCount(cityCount + 1);
                                }}>换一批</Button>
                            </Spin>
                        </Space>
                    </div>
                    <div style={{marginTop:8}}>
                        <Space size="large">
                            <div style={{ fontSize: 18, fontWeight: "bold" }}>本校：
                                {schoolSortList?.length > 0 ? (
                                    schoolSortList?.map((item, index) => {
                                        return (
                                            <span style={{ marginLeft: 16 }} key={index}>
                                                {`${item?.name}(${item?.value}%)`}
                                            </span>
                                        )
                                    })
                                ) : null}
                            </div>
                            <Spin spinning={schoolSpinning}>
                                <Button type='link' style={{ color: "#4ABB6A", fontSize: 18 }} icon={<SyncOutlined />} onClick={() => {
                                    setSchoolCount(schoolCount + 1);
                                }}>换一批</Button>
                            </Spin>
                        </Space>

                    </div>
                </div>
            </Modal>
        </>
    );

};


export default forwardRef(StudentGroup);