import { useState, useEffect, useRef } from 'react';
import { Space, Select, Button,  Table,Tag } from 'antd';
import { getTeacherSort } from '@/apis/leader';
import { getSubjectList,getSort } from '@/apis/common';
import SchoolChoice from '@/components/SchoolChoice';
import TeacherGroup from '@/components/TeacherGroup';
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 TeacherCrowd = (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 [expandedRowKeys, setExpandedRowKeys] = useState([]);

    const [sortList, setSortList] = useState([]);
    const [selectSort, setSelectSort] = useState();

    

    const teacherGroupRef = useRef();

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

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

    const expandableConfig = {
        expandedRowKeys: expandedRowKeys,
        defaultExpandedRowKeys: [dataSource?.[0]?.id],
        onExpand: (expanded, record) => {
            if (expanded) {
                setExpandedRowKeys([...expandedRowKeys, record.id]);
            } else {
                setExpandedRowKeys(expandedRowKeys?.filter((k) => k !== record.id));
            }
        },
    };


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

    useEffect(() => {

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

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


    const init = async () => {
        setLoading(true);
        try {
            const res = await getTeacherSort({
                examId,
                subjectId: subjectId,
                limitStudent: selectSort,
                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",
                                render: (_, record) => {
                                    return (<Button type="link" style={{ color: "#4ABB6A" }} onClick={() => {
                                        
                                        setTeacherGroupParams({
                                            examId,
                                            subjectId,
                                        });
                                        setRecord(record);
                                        teacherGroupRef.current?.openModal();

                                    }}>{record?.name}</Button>)
                                }
                            }
                        }
                        if (['教师姓名', '所属学校'].includes(item?.label)) {
                            return {
                                title: item?.label,
                                dataIndex: item?.prop,
                                align: "center",
                            }
                        }
                        return {
                            title: item?.label,
                            dataIndex: item?.prop,
                            align: "center",
                            sorter: (a, b) => a[item?.prop] - b[item?.prop],
                        }
                    })
                })
            }
            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 getSortInit = async () => {
        try {
            const res = await getSort();
            if (res?.code === 200) {

                setSortList(res?.data || []);
                setSelectSort(res?.data?.[0]?.value);
            }

        } catch (error) {
            console.log(error, 'get-sort-init-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');

        }
    };

    const handleSortClick = (item) => {
        setSelectSort(item?.value);
    };

    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);
                                        }} />
                                    </Space>
                                </section>
                                { actionShow && (<Button type='primary' style={{ fontSize: 16 }} onClick={handleDownload}>导出表格</Button>)}
                            </section>
                            <Space style={{ marginBottom: 8 }}>
                                {sortList.length > 0 ? (
                                    sortList.map((item, index) => {
                                        const isSelected = item?.value === selectSort;
                                        return (
                                            <Tag
                                                onClick={() => handleSortClick(item)}
                                                color={isSelected ? 'green' : 'default'}
                                                key={index}
                                                style={{
                                                    cursor: 'pointer',
                                                }}
                                            >
                                                {item?.label}
                                            </Tag>
                                        );
                                    })
                                ) : null}
                            </Space>
                            <section className={styles.analysis_content_table_content}>
                                <Table
                                    {...tableCommonProps}
                                    dataSource={dataSource}
                                    columns={columns}
                                    loading={loading}
                                    expandable={expandableConfig}
                                >
                                </Table>
                            </section>
                        </section>

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

        </div>
    );
};

export default TeacherCrowd;