import { useState, useEffect, useRef } from 'react';
import { Space, Select, Button, Table, Input } from 'antd';
import { getTeacherAvg, getTeacherZScoreAnalysis } from '@/apis/leader';
import { getSubjectList, getExam } from '@/apis/common';
import ScreenPage from "@/components/ScreenPage";
import SchoolChoice from '@/components/SchoolChoice';
import TeacherGroup from '@/components/TeacherGroup';
import Flex from "@/components/Flex";
import { tableCommonProps } from '@/utils/config.js';
import { downloadTableData } from '@/apis/download';
import { downloadExcelFile } from '@/utils/file';
import sectionSrc from '@/assets/icon/analysis-catalogue-3.png';
import upSrc from "@/assets/image/up.png";
import downSrc from "@/assets/image/down.png";
import styles from './index.less';



const TeacherPerformance = (props) => {

    const { examId = '', subtitle = '', idx = '' ,actionShow = true } = props;

    const [dataSource, setDataSource] = useState([]);
    const [columns, setColumns] = useState([]);
    const [responseData, setResponseData] = useState({});
    const [loading, setLoading] = useState(false);
    const [subjectId, setSubjectId] = useState("");
    const [subjectName, setSubjectName] = useState(null);
    const [schoolIds, setSchoolIds] = useState([]);
    const [limit, setLimit] = useState(50);


    const teacherGroupRef = useRef();

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

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

    const [examList, setExamList] = useState([]);


    const [isShow, setIsShow] = useState(false);



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

    useEffect(() => {

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

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


    const init = async () => {
        setLoading(true);
        try {
            const res = await getTeacherZScoreAnalysis({
                examId,
                subjectId,
                limit,
                schools: schoolIds,
                examIds: examList?.map(item => item?.id).filter(item => item !== examId),
            });
            if (res.code === 200) {
                setLoading(false);
                setResponseData(res);
                setDataSource(res?.data || []);
                setColumns(() => {
                    return res?.columns?.map(item => {
                        if (item?.label === '教师姓名') {
                            return {
                                title: item?.label,
                                dataIndex: item?.prop,
                                align: "center",
                                width: 140,
                                render: (_, record) => {
                                    return (<Button type="link" style={{ color: "#4ABB6A" }} onClick={() => {
                                        setTeacherGroupParams({
                                            examId,
                                            subjectId: subjectId
                                        });
                                        setRecord(record);
                                        teacherGroupRef.current?.openModal();

                                    }}>{record?.name}</Button>)
                                }
                            }
                        }
                        if (['对比考试均分', 'z值', '修正后z值'].includes(item?.label)) {
                            return {
                                title: item?.label,
                                dataIndex: item?.prop,
                                align: "center",
                                sorter: (a, b) => a[item?.prop] - b[item?.prop],
                            }
                        }
                        return {
                            title: item?.label,
                            dataIndex: item?.prop,
                            align: "center",
                        }
                    })
                })

                return;
            }
            setLoading(false);
        } catch (error) {
            setLoading(false);
            console.log(error, 'teacher-error');
        }

    };


    const singleSubjectInit = async () => {
        try {
            const res = await getSubjectList();
            if (res?.code === 200) {
                setSubjectId(res?.data?.[0]?.id || '');
                setSubjectName(res?.data?.[0]?.cname || null);
                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, `${subtitle}*${subjectName}教师绩效Z值情况分析`);
            }

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

        }
    };


    return (
        <div>
            <section className={styles.analysis_content_table} id={`operationExport${idx}`}>
                <section className={styles.analysis_content_table_title}>
                    <section className={styles.page_title}>
                        <img src={sectionSrc} className={styles.page_title_img} />
                        <span className={styles.page_title_text}>教师绩效Z值情况分析</span>
                    </section>
                    {actionShow && ( <Button type='primary' style={{ fontSize: 16 }} onClick={handleDownload}>导出表格</Button>)}
                </section>
                <section style={{ display: "flex", alignItems: "center" }}>
                    <p className={styles.performance_label}>当前考试：{subtitle}{subjectName}</p>
                    <Space>
                        <Select
                            placeholder="请选择学科"
                            options={singleSubjectList}
                            value={subjectName}
                            style={{ marginLeft: 20, width: "120px" }}
                            onChange={(value, options) => {
                                if (!value) {
                                    return;
                                }
                                setSubjectName(options?.label);
                                setSubjectId(value);
                            }}
                        />
                        <SchoolChoice onChange={(value) => {
                            setSchoolIds(value);
                        }} />
                        <Flex
                            alignItems="center"
                        >
                            全市前&nbsp;&nbsp;
                            <Input
                                style={{
                                    padding: "2px 8px",
                                    border: "1px solid #c0c0c0",
                                    borderRadius: 5,
                                    cursor: "pointer",
                                    color: "#c0c0c0",
                                    width: 80,
                                }}
                                min={1}
                                placeholder="请输入"
                                value={limit}
                                type="number"
                                onChange={(e) => {
                                    setLimit(+e.target.value);
                                }}
                            />
                            &nbsp;&nbsp;名
                        </Flex>
                    </Space>
                </section>
                <section>
                    <div className={styles.performance_select}>
                        <span>对比考试：</span>
                        {examList?.filter((item) => item?.id !== examId)?.map((item) => {
                            return (
                                <div
                                    style={{ color: "#333", marginRight: 8 }}
                                    key={item?.id}
                                    closable
                                    onClose={(e) => {
                                        e.preventDefault();
                                        setExamList((prev) => {
                                            return prev.filter((i) => i?.id !== item?.id)
                                        })
                                    }}
                                >
                                    {`${item?.term}*${item?.semester}*${item?.examName};`}
                                </div>
                            );
                        })}
                        <Flex
                            style={{
                                border: "1px solid #666",
                                borderRadius: 5,
                                cursor: "pointer",
                                marginLeft: 8,
                                width: 110,
                                padding: "0px 8px",
                            }}
                            alignItems="center"
                            onClick={() => {
                                setIsShow(!isShow);
                            }}
                        >
                            选择考试
                            <img
                                src={isShow ? upSrc : downSrc}
                                width={14}
                                height={12}
                                style={{ marginLeft: 5 }}
                            />
                        </Flex>
                    </div>
                </section>

                <div>
                    <ScreenPage
                        isShow={isShow}
                        isSingle={false}
                        isShowSubject={false}
                        isShowSchool={false}
                        isTeacher={true}
                        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 => {
                                console.log(res.data);
                                if (res.code === 200) {
                                    setExamList(res.data || []);
                                }

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

                            })
                        }}

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

                <section className={styles.analysis_content_table_content}>
                    <Table
                        {...tableCommonProps}
                        dataSource={dataSource}
                        columns={columns}
                        loading={loading}
                        rowKey="teacherId"
                    >
                    </Table>
                </section>
            </section>

            <TeacherGroup ref={teacherGroupRef} params={teacherGroupParams} record={record} />

        </div>
    );
};

export default TeacherPerformance;