import { useState, useEffect, useImperativeHandle, forwardRef, memo } from "react";
import { Modal,Table,Button } from "antd";
import ScreenPage from "@/components/ScreenPage";
import Flex from "@/components/Flex";
import { getTeacherAnalysis, getTeacherZScoreAnalysis, getTeacherTrace, getTeacherGrade, getTeacherSort, getTeacherAvg, getSingleTeacherZ } from '@/apis/leader';
import { getExam } from "@/apis/common";
import { downloadTableData } from '@/apis/download';
import { downloadExcelFile } from '@/utils/file';
import upSrc from "@/assets/image/up.png";
import downSrc from "@/assets/image/down.png";
import styles from "./index.less";

const TeacherGroup = (props,ref) => {

    const { record = {}, params = {} } = props;
    


    const [open, setOpen] = useState(false);
    const [isShow, setIsShow] = useState(false);
    const [isShow1, setIsShow1] = useState(false);
    const [responseData1, setResponseData1] = useState({});
    const [responseData2, setResponseData2] = useState({});
    const [responseData3, setResponseData3] = useState({});
    const [examId, setExamId] = useState('');
    const [subTitle, setSubTitle] = useState('');
    const [examList, setExamList] = useState([]);

    const [columns1, setColumns1] = useState([]);
    const [columns2, setColumns2] = useState([]);
    const [columns3, setColumns3] = useState([]);

    const [loading1, setLoading1] = useState(false);
    const [loading2, setLoading2] = useState(false);
    const [loading3, setLoading3] = useState(false);

    const [dataSource1, setDataSource1] = useState([]);
    const [dataSource2, setDataSource2] = useState([]);
    const [dataSource3, setDataSource3] = useState([]);



    useImperativeHandle(ref, () => ({
        openModal,
        closeModal
    }));

    useEffect(() => {
        if (open) {
            trackInit();
            gradeInit();
        }
    }, [open]);


    useEffect(()=>{
        if(open && examList?.length > 0 || !examId) {
            singleTeacherZ();
        }

    },[open,examList,examId])


    const trackInit = async () => {
        try {
            setLoading1(true);
            const res = await getTeacherTrace({
                teacher: record?.teacherId,
                examId: params?.examId,
                subjectId: params?.subjectId
            });
            if (res?.code === 200) {
                setResponseData1(res);
                setLoading1(false);
                setDataSource1(res?.data || []);
                setColumns1(() => {
                    return res?.columns?.map(item => {
                        return {
                            title: item?.label,
                            dataIndex: item?.prop,
                            align: "center",
                        }
                    });
                })
                return;
            }
            setLoading1(false);
        } catch (error) {
            setLoading1(false);
            console.log(error, 'track-error');

        }
    };

    const gradeInit = async () => {
        try {
            setLoading2(true);
            const res = await getTeacherGrade({
                teacher: record?.teacherId,
                examId: params?.examId,
                subjectId: params?.subjectId
            });
            if (res?.code === 200) {
                setResponseData2(res);
                setLoading2(false);
                setDataSource2(res?.data || []);
                setColumns2(() => {
                    return res?.columns?.map(item => {
                        return {
                            title: item?.label,
                            dataIndex: item?.prop,
                            align: "center",
                        }
                    });
                })
                return;
            }
            setLoading2(false);
        } catch (error) {
            setLoading2(false);
            console.log(error, 'track-error');

        }

    };


    const singleTeacherZ = async () => {
        try {
            setLoading3(true);
            const res = await getSingleTeacherZ({
                teacher: record?.teacherId,
                examId,
                subjectId: params?.subjectId,
                examIds: examList?.map(item => item?.id).filter(item=>item !== examId),
            });
            if (res?.code === 200) {
                setResponseData3(res);
                setLoading3(false);
                setDataSource3(res?.data || []);
                setColumns3(() => {
                    return res?.columns?.map(item => {
                        return {
                            title: item?.label,
                            dataIndex: item?.prop,
                            align: "center",
                        }
                    });
                })
                return;
            }
            setLoading3(false);
        } catch (error) {
            setLoading3(false);
            console.log(error, 'track-error');

        }

    };

    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}教师增量评价`);
            }

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

        }
    };

    const tableCommonProps = {
        style: { maxHeight: 460},
        rowKey: "teacherId",
        scroll: { x: 1400,y:340 },
        sticky: true,
        pagination: false,
    };

    const openModal = () => {
        setOpen(true);
    };

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

    return (
        <div className={styles.teacher}>
            <Modal
                title={`教师成长性：${record?.school}*${record?.name}`}
                width={'80vw'}
                open={open}
                centered
                styles={{ body: { height: "80vh"} }}
                maskClosable={false}
                destroyOnClose
                onCancel={() => {
                    setOpen(false);
                }}
                onOk={() => {
                    setOpen(false);
                }}
            >
                <Flex
                    direction="column"
                    style={{ overflowY: "scroll", height: "80vh" }}
                >
                    <Flex style={{ color: "#666" }}>教师情况跟踪：</Flex>
                    <Table
                        dataSource={dataSource1}
                        columns={columns1}
                        loading={loading1}
                        {...tableCommonProps}
                    ></Table>
                    <Flex>
                        <Button
                            style={{
                                backgroundColor: "#4abb6a",
                                color: "#fff",
                                marginTop: 8,
                            }}
                            onClick={handleDownload1}
                        >
                            导出表格
                        </Button>
                    </Flex>
                    <Flex style={{ color: "#666" }}>教师成绩分析：</Flex>
                    <Table
                        dataSource={dataSource2}
                        columns={columns2}
                        loading={loading2}
                        {...tableCommonProps}

                    ></Table>

                    <Flex>
                        <Button
                            style={{
                                backgroundColor: "#4abb6a",
                                color: "#fff",
                                marginTop: 8,
                            }}
                            onClick={handleDownload2}
                        >
                            导出表格
                        </Button>
                    </Flex>
                    <ScreenPage
                        isShow={isShow1}
                        isSingle={true}
                        isShowSubject={false}
                        isTeacher={true}
                        isShowSchool={false}
                        onChange={(e) => {
                            setSubTitle([e?.currentGrade?.[0]?.name, e?.currentSemester?.[0]?.name, e?.currentExamination?.[0]?.name].filter(item => !!item).join("*"));
                            setExamId(e?.examId || '');
                        }}

                        saveshow={(e) => {
                            setIsShow1(e);
                        }}
                    />
                    <h3 style={{marginTop:16}}>教师增量评价：{record?.name}</h3>
                    <Flex
                        style={{
                            width: "100%",
                            display: "flex",
                            alignItems: "center",
                            margin: "5px 0",
                            // gap: 12,
                        }}
                        justify="space-between"
                        alignItems="center"
                    >
                        <Flex style={{ flex: 1 }} alignItems="center">
                            <Flex
                                alignItems="center"
                                style={{
                                    width: "100%",
                                    display: "flex",
                                    alignItems: "center",
                                    color: "#666",
                                }}
                            >
                                <Flex>当前考试 : &nbsp;</Flex>
                                <Flex style={{ width: "92%" }} wrap="wrap">
                                    <h3 style={{color:'#000'}}> {subTitle}</h3>
                                </Flex>
                            </Flex>
                        </Flex>

                        <Flex
                            style={{
                                padding: "4px 8px",
                                border: "1px solid #666",
                                borderRadius: 5,
                                cursor: "pointer",
                                marginLeft: 10,
                            }}
                            alignItems="center"
                            onClick={() => {
                                setIsShow1(true)
                            }}
                        >
                            选择考试
                            <img
                                src={isShow1 ? upSrc : downSrc}
                                width={14}
                                height={12}
                                style={{ marginLeft: 5 }}
                            />
                        </Flex>
                    </Flex>
                    <ScreenPage
                        isShow={isShow}
                        isSingle={false}
                        isShowSubject={false}
                        isTeacher={true}
                        isShowSchool={false}
                        onChange={(e) => {
                            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) => {
                            setIsShow(e);
                        }}
                    />
                    <Flex
                        style={{
                            width: "100%",
                            display: "flex",
                            alignItems: "center",
                            margin: "5px 0",
                            // gap: 12,
                        }}
                        justify="space-between"
                        alignItems="center"
                    >
                        <Flex style={{ flex: 1 }} alignItems="center">
                            <Flex
                                alignItems="center"
                                style={{
                                    width: "100%",
                                    display: "flex",
                                    alignItems: "center",
                                    color: "#666",
                                }}
                            >
                                <Flex>对比考试 : &nbsp;</Flex>
                                <Flex style={{ width: "92%" }} wrap="wrap">
                                    {examList?.filter((item) => item?.id !== params?.examId)?.map((item) => {
                                        return (
                                            <h3
                                                style={{ color: "#000", marginRight: 8 }}
                                                key={item?.id}

                                            >
                                                {`${item?.term}*${item?.semester}*${item?.examName};`}
                                            </h3>
                                        );
                                    })}
                                </Flex>
                            </Flex>
                        </Flex>

                        <Flex
                            style={{
                                padding: "4px 8px",
                                border: "1px solid #666",
                                borderRadius: 5,
                                cursor: "pointer",
                                marginLeft: 10,
                            }}
                            alignItems="center"
                            onClick={() => {
                                setIsShow(true)
                            }}
                        >
                            选择考试
                            <img
                                src={isShow ? upSrc : downSrc}
                                width={14}
                                height={12}
                                style={{ marginLeft: 5 }}
                            />
                        </Flex>
                    </Flex>
                    <Table
                        dataSource={dataSource3}
                        columns={columns3}
                        loading={loading3}
                        {...tableCommonProps}
                    >
                    </Table>
                    <Flex>
                        <Button
                            style={{
                                backgroundColor: "#4abb6a",
                                color: "#fff",
                                marginTop: 8,
                            }}
                            onClick={handleDownload3}
                        >
                            导出表格
                        </Button>
                    </Flex>
                    <Flex style={{ width: '100%', marginTop: 32 }} justify="center" alignItems="center">
                        <Button type="primary" style={{
                            backgroundColor: "#4abb6a",
                            color: "#fff",
                            marginTop: 10,
                        }}>{record?.name}课堂实录</Button>
                    </Flex>
                </Flex>
            </Modal>
        </div>
    )
};

export default memo(forwardRef(TeacherGroup));