import { useState, useEffect, useRef } from 'react';
import { Space, Select, Button, Table, Input } from 'antd';
import { getTeacherAvg } from '@/apis/leader';
import { getSubjectList } from '@/apis/common';
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 styles from './index.less';



const TeacherAverage = (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([]);




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

    useEffect(() => {

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

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


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

                                    }}>{record?.name}</Button>)
                                }
                            }
                        }
                        return {
                            title: item?.label,
                            dataIndex: item?.prop,
                            align: "center",
                            width: 80,
                            sorter: item?.sortable ? (a, b) => a[item?.prop] - b[item?.prop] : false,
                        }
                    })
                })

            }
            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}教师群体均分分析`);
            }

        } 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}>{subtitle}教师群体均分分析</span>
                        <Space>
                            <Select
                                placeholder="请选择学科"
                                options={singleSubjectList}
                                value={subjectName}
                                style={{ marginLeft: 20, width: "120px" }}
                                onChange={(value, options) => {
                                    if (!value) {
                                        return;
                                    }
                                    setSubjectName(options?.label);
                                    setSubjectId(value);
                                }}
                            />
                            <SchoolChoice onChange={(value) => {
                                setSchoolIds(value);
                            }} />
                            <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>
                    {actionShow && (<Button type='primary' style={{ fontSize: 16 }} onClick={handleDownload}>导出表格</Button>)}
                </section>
                <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 TeacherAverage;