import { useState, useEffect, useRef } from 'react';
import { Space, Button, Spin, Table } from 'antd';
import { getCombinationDistribution } from '@/apis/leader';
import SchoolChoice from '@/components/SchoolChoice';
import Echarts from "@/components/Echarts";
import { tableCommonProps } from '@/utils/config.js';
import { downloadTableData } from '@/apis/download';
import { downloadExcelFile } from '@/utils/file';
import sectionSrc from '@/assets/icon/analysis-catalogue-5.png';
import styles from './index.less';

const CombineExaminationSubject = (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 [schoolIds, setSchoolIds] = useState([]);
    const [expandedRowKeys, setExpandedRowKeys] = useState([]);
    const [echartData1, setEchartData1] = useState({});
    const [echartData2, setEchartData2] = useState({});
    const [lengButton, setLengButton] = useState([]);
    const echartRef = useRef();

    const [selectTag, setSelectTag] = useState('');
    const [navTags, setNavTags] = useState([]);
    const [allEchartData, setAllEchartData] = useState({});
    const [selectedNavTag, setSelectedNavTag] = 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(() => {
        if (!selectedNavTag) {
            return;
        }

        const obj = {
            num: allEchartData?.num?.filter(item => item?.lineName === selectedNavTag),
            rate: allEchartData?.rate?.filter(item => item?.lineName === selectedNavTag),

        };

        setEchartData1(() => {
            return {
                xAxis: {
                    name: "",
                    type: "category",
                    axisTick: { show: false },
                    data: obj.num?.[0]?.xdata,
                },
                yAxis: {
                    name: "",
                },
                tooltip: {
                    show: true,
                },
                yChartData: [
                    {
                        name: '人数',
                        data: obj.num?.[0]?.data
                    }
                ]
            }
        });

        setEchartData2(() => {
            return {
                xAxis: {
                    name: "",
                    type: "category",
                    axisTick: { show: false },
                    data: obj.rate?.[0]?.xdata,
                },
                yAxis: {
                    name: "人数占比",
                },
                tooltip: {
                    show: true,
                },
                yChartData: [
                    {
                        name: '人数占比',
                        data: obj.rate?.[0]?.data
                    }
                ]
            }
        });
    }, [selectedNavTag]);

    useEffect(() => {

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

    }, [examId, schoolIds]);


    const init = async () => {
        setLoading(true);
        try {
            const res = await getCombinationDistribution({
                examId,
                schools: schoolIds
            });
            if (res?.code === 200) {
                setLoading(false);
                setResponseData(res);
                setExpandedRowKeys([res?.data?.[0]?.id,res?.data?.[0]?.children?.[0]?.id]);
                setDataSource(res?.data || []);
                setColumns(() => {
                    return res?.columns?.map(item => {
                        return {
                            title: item?.label,
                            dataIndex: item?.prop,
                            align: "center",
                            width: 150,
                            sorter: item?.sortable ? (a, b) => a[item?.prop] - b[item?.prop] : false,
                            children: item?.children?.map(element => {
                                return {
                                    title: element?.label,
                                    dataIndex: element?.prop,
                                    align: "center",
                                    width: 160,
                                    sorter: element?.sortable ? (a, b) => a[element?.prop] - b[element?.prop] : false
                                }
                            })
                        }
                    });
                });

                if (!res?.columnDiagramResult || !res?.columnDiagramResult?.num?.length > 0 || !res?.columnDiagramResult?.rate?.length > 0) {
                    return;
                }

                const selectedName = res?.columnDiagramResult?.num?.map(item => item?.lineName)[0];
                setNavTags(res?.columnDiagramResult?.num?.map(item => item?.lineName));
                setSelectedNavTag(selectedName);
                setLengButton(['人数', '人数占比']);
                setSelectTag('人数');

                setAllEchartData(res?.columnDiagramResult);

                const obj = {
                    num: res?.columnDiagramResult?.num?.filter(item => item?.lineName === selectedName),
                    rate: res?.columnDiagramResult?.rate?.filter(item => item?.lineName === selectedName),
                };

                setEchartData1(() => {
                    return {
                        xAxis: {
                            name: "",
                            type: "category",
                            axisTick: { show: false },
                            data: obj.num?.[0]?.xdata,
                        },
                        yAxis: {
                            name: "人数",
                        },
                        tooltip: {
                            show: true,
                        },
                        yChartData: [
                            {
                                name: '人数',
                                data: obj.num?.[0]?.data
                            }
                        ]
                    }
                });
                setEchartData2(() => {
                    return {
                        xAxis: {
                            name: "",
                            type: "category",
                            axisTick: { show: false },
                            data: obj.rate?.[0]?.xdata,
                        },
                        yAxis: {
                            name: "人数占比",
                        },
                        tooltip: {
                            show: true,
                        },
                        yChartData: [
                            {
                                name: '人数占比',
                                data: obj.rate?.[0]?.data
                            }
                        ]
                    }
                });
            }
            setLoading(false);
        } catch (error) {
            setLoading(false);
            console.log(error, 'paramsInit-error');

        }
    };


    const handleDownload = async () => {
        try {
            const res = await downloadTableData(responseData);
            if (res?.status === 200) {
                downloadExcelFile(res, `${subtitle}*${selectedNavTag}选考组合分布分析`);
            }

        } 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>
                            <SchoolChoice onChange={(value) => {
                                setSchoolIds(value);
                            }} />
                        </section>
                        {actionShow && (<Button type='primary' style={{ fontSize: 16 }} onClick={() => {
                            echartRef?.current?.exportChart();
                        }}>导出图表</Button>)}
                    </section>
                    <section className={styles.analysis_content_chart_content}>
                        <Space style={{ marginBottom: 8 }}>
                            {navTags?.map((item, index) => {
                                return (
                                    <Button
                                        key={index}
                                        type={item === selectedNavTag ? 'primary' : 'default'}
                                        size="small"
                                        onClick={() => {
                                            setSelectedNavTag(item);
                                        }}
                                    >
                                        {item}
                                    </Button>
                                )
                            })}
                        </Space>
                        <Spin spinning={loading} tip='计算中，请稍后'>

                            {lengButton?.length > 0 ? (
                                <Space>
                                    {lengButton?.map((item, index) => {
                                        return (
                                            <Button
                                                key={index}
                                                type={item === selectTag ? 'primary' : 'default'}
                                                size="small"
                                                onClick={() => {
                                                    setSelectTag(item);
                                                }}
                                            >
                                                {item}
                                            </Button>
                                        )
                                    })}
                                </Space>

                            ) : null}
                            {selectTag === '人数' ? (<Echarts
                                isShow={false}
                                data={echartData1}
                                hasExport={false}
                                ref={echartRef}
                                type='bar'
                                text={`选考组合分布分析*${subtitle}${selectedNavTag}*人数`}
                                lengButton={['人数']}
                                hasTable={false}
                            />) : null}
                            {selectTag === '人数占比' ? (<Echarts
                                isShow={false}
                                type="bar"
                                data={echartData2}
                                ref={echartRef}
                                hasTable={false}
                                hasExport={false}
                                text={`选考组合分布分析*${subtitle}${selectedNavTag}*人数占比`}
                                lengButton={['人数占比']}
                            />) : null}
                        </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>
                            <SchoolChoice onChange={(value) => {
                                setSchoolIds(value);
                            }} />
                        </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}
        </div>
    );
};

export default CombineExaminationSubject;