import { useState, useEffect, useRef, useMemo } from 'react';
import { Space, Select, Button, Spin, Empty, Table } from 'antd';
import { getAssignDistribution } from '@/apis/leader';
import { getSubjectListCombineList } from '@/apis/common';
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 OptionalExaminationScoring = (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 [navTags, setNavTags] = useState([]);
    const [selectedNavTag, setSelectedNavTag] = useState('');
    const [allEchartData, setAllEchartData] = useState({});
    const [selectTag, setSelectTag] = useState('');

    const [singleSubjectList, setSingleSubjectList] = 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));
            }
        },
    };



    const computedChartType = useMemo(() => {
        if (['人数', '累计人数'].includes(selectTag)) {
            return 'bar';
        }
        return "pie"

    }, [selectTag]);

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

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

    }, [examId, schoolIds, subjectId]);


    const init = async () => {
        try {
            setLoading(true);
            const res = await getAssignDistribution({
                examId,
                subjectId: subjectId,
                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,
                            children: item?.children?.map(element => {
                                return {
                                    title: element?.label,
                                    dataIndex: element?.prop,
                                    align: "center",
                                    width: 140,
                                    sorter: (a, b) => a[element?.prop] - b[element?.prop],
                                }
                            })
                        }
                    })
                });
                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(['人数', '人数占比', '累计人数', '累计人数占比']);
                setAllEchartData(res?.columnDiagramResult);
                const obj = {
                    num: res?.columnDiagramResult?.num?.filter(item => item?.lineName === selectedName),
                    rate: res?.columnDiagramResult?.rate?.filter(item => item?.lineName === selectedName),
                    numCumulative: res?.columnDiagramResult?.numCumulative?.filter(item => item?.lineName === selectedName),
                    rateCumulative: res?.columnDiagramResult?.rateCumulative?.filter(item => item?.lineName === selectedName),
                };
                setSelectTag('人数');
                ['num', 'rate', 'numCumulative', 'rateCumulative'].forEach(key => {
                    obj[key].forEach(item => {
                        // 创建临时存储容器
                        const filtered = [];

                        // 同步过滤 data 和 xdata
                        item.data.forEach((value, index) => {
                            if (value !== 0) {
                                filtered.push({
                                    data: value,
                                    x: item.xdata[index]
                                });
                            }
                        });

                        // 更新原数组
                        item.data = filtered.map(e => e.data);
                        item.xdata = filtered.map(e => e.x);
                    });
                });

                setEchartData(() => {
                    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
                            }
                        ]
                    }
                });
            }
            setLoading(false);
        } catch (error) {
            setLoading(false);
            console.log(error, 'init-error');

        }
    };


    const singleSubjectInit = async () => {
        try {
            const res = await getSubjectListCombineList();
            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');

        }
    };


    // 监听selectedNavTag 筛选出该科目的人数和人数占比
    useEffect(() => {
        if (!selectedNavTag) {
            return;
        }

        const obj = {
            num: allEchartData?.num?.filter(item => item?.lineName === selectedNavTag),
            rate: allEchartData?.rate?.filter(item => item?.lineName === selectedNavTag),
            numCumulative: allEchartData?.numCumulative?.filter(item => item?.lineName === selectedNavTag),
            rateCumulative: allEchartData?.rateCumulative?.filter(item => item?.lineName === selectedNavTag),
        };
        ['num', 'rate', 'numCumulative', 'rateCumulative'].forEach(key => {
            obj[key].forEach(item => {
                // 创建临时存储容器
                const filtered = [];

                // 同步过滤 data 和 xdata
                item.data.forEach((value, index) => {
                    if (value !== 0) {
                        filtered.push({
                            data: value,
                            x: item.xdata[index]
                        });
                    }
                });

                // 更新原数组
                item.data = filtered.map(e => e.data);
                item.xdata = filtered.map(e => e.x);
            });
        });


        const filterData = (selectTag) => {
            if (selectTag === '人数') {
                return {
                    xAxis: {
                        name: "",
                        type: "category",
                        axisTick: { show: false },
                        data: obj.num?.[0]?.xdata,
                    },
                    yAxis: {
                        name: '人数',
                    },
                    tooltip: {
                        show: true,
                    },
                    yChartData: [
                        {
                            name: selectTag,
                            data: obj.num?.[0]?.data
                        }
                    ]
                };
            }
            if (selectTag === '人数占比') {
                return {
                    yChartData: obj.rate?.[0]?.xdata.map((item, index) => {
                        return {
                            name: item,
                            data: [obj.rate?.[0]?.data?.[index]]
                        }
                    })
                };
            }
            if (selectTag === '累计人数') {
                return {
                    xAxis: {
                        name: "",
                        type: "category",
                        axisTick: { show: false },
                        data: obj?.numCumulative?.[0]?.xdata,
                    },
                    yAxis: {
                        name: '人数',
                    },
                    tooltip: {
                        show: true,
                    },
                    yChartData: [
                        {
                            name: selectTag,
                            data: obj?.numCumulative?.[0]?.data
                        }
                    ]
                };
            }
            if (selectTag === '累计人数占比') {
                return {
                    yChartData: obj.rateCumulative?.[0]?.xdata.map((item, index) => {
                        return {
                            name: item,
                            data: [obj.rateCumulative?.[0]?.data?.[index]]
                        }
                    })
                };
            }
        }
        setEchartData(filterData(selectTag));

    }, [selectedNavTag, selectTag]);

    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={singleSubjectList}
                            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}>

                <Space style={{ marginBottom: 8 }} wrap>
                    {navTags?.map((item, index) => {
                        return (
                            <Button
                                key={index}
                                type={item === selectedNavTag ? 'primary' : 'default'}
                                size="small"
                                onClick={() => {
                                    setSelectedNavTag(item);
                                }}
                            >
                                {item}
                            </Button>
                        )
                    })}

                </Space>
                <section style={{ marginBottom: 16 }}>
                    <Space >
                        {lengButton?.map((item, index) => {
                            return (
                                <Button
                                    key={index}
                                    type={item === selectTag ? 'primary' : 'default'}
                                    size="small"
                                    onClick={() => {
                                        setSelectTag(item);
                                    }}
                                >
                                    {item}
                                </Button>
                            )
                        })}
                    </Space>
                </section>
                <Spin spinning={loading} tip='计算中，请稍后'>
                    {lengButton?.length > 0 ? (<Echarts
                        ref={echartRef}
                        hasTable={false}
                        hasExport={false}
                        data={echartData}
                        type={computedChartType}
                        isShow={false}
                        text={`${subtitle}${subjectName}*${selectTag}*选考赋分分析-图表`}
                        lengButton={[selectTag]}

                    />) : <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={singleSubjectList}
                            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}

    </div>);
}

export default OptionalExaminationScoring;