import { useState, useEffect, useRef } from 'react';
import { Space, Select, Button, Spin, Empty, Table } from 'antd';
import { getSchoolPercentAnalysis } from '@/apis/leader';
import { getSubjectListAll } from '@/apis/common';
import SchoolChoice from '@/components/SchoolChoice';
import Echarts from "@/components/Echarts";
import StudentGroup from '@/components/StudentGroup';
import { tableCommonProps } from '@/utils/config.js';
import { downloadTableData } from '@/apis/download';
import { downloadExcelFile } from '@/utils/file';
import { buildEchartData, removeEmptyChildren } from '@/utils/table';
import sectionSrc from '@/assets/icon/analysis-catalogue-2.png';
import styles from './index.less';



const SchoolPercentage = (props) => {


    const { examId = '', subtitle = '', isShowChart = false, isShowTable = false,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 [echartData, setEchartData] = useState({});
    const [lengButton, setLengButton] = useState([]);
    const echartRef = useRef();

    const studentGroupRef = useRef();
    const [title, setTitle] = useState('');
    const [studentGroupParams, setStudentGroupParams] = useState({});

    const [allSubjectList, setAllSubjectList] = useState([]);

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


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

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

    }, [examId, schoolIds, subjectId]);


    const init = async () => {
        try {
            setLoading(true);
            const res = await getSchoolPercentAnalysis({
                examId,
                subjectId: subjectId,
                schools: schoolIds
            });
            if (res?.code === 200) {
                setLoading(false);
                setResponseData(res);
                setExpandedRowKeys([res?.data?.[0]?.id,res?.data?.[0]?.children?.[0]?.id]);
                const list = removeEmptyChildren(res.data);
                setDataSource(list);
                const data = buildEchartData(res?.columnDiagramResult?.num);
                setEchartData(data);
                setLengButton(res?.columnDiagramResult?.num?.map(item => item?.lineName) || []);
                setColumns(() => {
                    return res?.columns?.map(item => {
                        return {
                            title: item?.label,
                            dataIndex: item?.prop,
                            align: "center",
                            width: 300,
                            children: item?.children?.map(element => {
                                if (element?.label === '人数') {
                                    return {
                                        title: element?.label,
                                        dataIndex: element?.prop,
                                        align: "center",
                                        width: 100,
                                        render: (text) => (
                                            <Button type="link" style={{ color: "#4ABB6A" }} onClick={() => {
                                                setTitle(text?.typeDisc);
                                                studentGroupRef.current?.openModal();
                                                setStudentGroupParams({
                                                    examId,
                                                    students: text?.data
                                                });
                                            }}>{text?.value}</Button>
                                        ),
                                    }
                                }
                                return {
                                    title: element?.label,
                                    dataIndex: element?.prop,
                                    width: element?.label === '人数排名' ? 100 : 150,
                                    align: "center",
                                    sorter: (a, b) => a[element?.prop] - b[element?.prop],
                                }
                            })
                        }
                    })

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

        }
    };

    const allSubjectInit = async () => {
        try {
            const res = await getSubjectListAll();
            if (res?.code === 200) {
                setSubjectId(res?.data?.[0]?.id || '');
                setSubjectName(res?.data?.[0]?.cname || null);
                setAllSubjectList(() => {
                    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>
            {isShowChart ? (<section className={styles.analysis_content_chart} id={`operationExport${idx}`} >
                <section className={styles.analysis_content_chart_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={allSubjectList}
                                value={subjectName}
                                style={{ marginLeft: 20, width: "120px" }}
                                allowClear
                                onChange={(value, option) => {
                                    if (!value) {
                                        setSubjectName(null);
                                        setSubjectId("");
                                        return;
                                    }
                                    setSubjectName(option?.label);

                                    setSubjectId(value);
                                }}
                            />
                            <SchoolChoice onChange={(value) => {
                                setSchoolIds(value);
                            }} />
                        </Space>
                    </section>
                    {actionShow && (<Button type='primary' style={{ fontSize: 16 }} onClick={() => {
                        echartRef?.current?.exportChart();
                    }}>导出图表</Button>)}
                </section>
                <section className={styles.analysis_content_chart_content}>
                    <Spin spinning={loading} tip='计算中，请稍后'>
                        {lengButton?.length > 0 ? (<Echarts
                            hasTable={false}
                            ref={echartRef}
                            hasExport={false}
                            data={echartData}
                            type={"bar"}
                            isShow={true}
                            text={`${subtitle}${subjectName}*学校排名百分比分析-图表`}
                            lengButton={lengButton}

                        />) : <Empty description={"暂无图表数据"} />}
                    </Spin>
                </section>
            </section>) : null}
            {isShowTable ? (<section className={styles.analysis_content_table} id={`operationExport${idx + 1}`}>
                <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={allSubjectList}
                                value={subjectName}
                                style={{ marginLeft: 20, width: "120px" }}
                                allowClear
                                onChange={(value, option) => {
                                    if (!value) {
                                        setSubjectName(null);
                                        setSubjectId("");
                                        return;
                                    }
                                    setSubjectName(option?.label);

                                    setSubjectId(value);
                                }}
                            />
                            <SchoolChoice onChange={(value) => {
                                setSchoolIds(value);
                            }} />
                        </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}
                        locale={{ emptyText: loading ? "计算中，请稍后" : "暂无数据" }}
                        loading={{ spinning: loading, tip: "计算中，请稍后" }}
                        expandable={expandableConfig}
                    >
                    </Table>
                </section>
            </section>) : null}
            <StudentGroup
                ref={studentGroupRef}
                params={studentGroupParams}
                title={title}
            />
        </div>
    );
};

export default SchoolPercentage;