import { useState, useEffect, useRef, useMemo } from 'react';
import { Space, Select, Button, Spin, Table, Tag } from 'antd';
import * as echarts from 'echarts';
import { getExamRanking } from '@/apis/exam';
import { getSubjectListAll, getSort } from '@/apis/common';
import SchoolChoice from '@/components/SchoolChoice';
import StudentGroup from '@/components/StudentGroup';
import { tableCommonProps } from '@/utils/config.js';
import { downloadTableData } from '@/apis/download';
import { downloadExcelFile } from '@/utils/file';
import navIconSrc from '@/assets/icon/analysis-navigation-icon.png';
import styles from './index.less';

const ContrastExamRanking = (props) => {
    const { examId = '', subtitle = '', examList = [], 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 [allSubjectList, setAllSubjectList] = useState([]);
    const [expandedRowKeys, setExpandedRowKeys] = useState([]);

    const [examSortList, setExamSortList] = useState([]);
    const [examSelectSort, setExamSelectSort] = useState();
    const [typeList, setTypeList] = useState([]);
    const [selectType, setSelectType] = useState('');
    const [allEchartDataRanking, setAllEchartDataRanking] = useState({});


    const [tags, setTags] = useState([]);
    const [selectedTags, setSelectedTags] = useState([]);
    const [echartXData, setEchartXData] = useState([]);

    const [mockChartData, setMockChartData] = useState([]);
    const chartRef = useRef(null);

    let chartInstance = null;
    const [echartImg, setEchartImg] = useState();


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


    const labelOption = {
        show: true,
        position: 'top',
        distance: 24,
        align: 'center',
        verticalAlign: 'middle',
        formatter: (params) => {
            return `${params.value}`
        },
        fontSize: 12,
        rich: {
            name: {}
        }
    };


    const commonSeries = {
        type: 'line',
        barGap: 0,
        label: labelOption,
        emphasis: {
            focus: 'series'
        },
    };

    const intersectionData = useMemo(() => {
        return mockChartData?.filter((item) =>
            selectedTags.includes(item.name),
        );
    }, [selectedTags, mockChartData]);

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

    useEffect(() => {
        if (!examId || !examList.length > 0 || !subjectId) {
            return;
        }
        init();

    }, [examId, schoolIds, subjectId, examList, examSelectSort]);


    useEffect(() => {
        if (selectType) {
            if (selectType === '人数') {
                setMockChartData(() => {
                    return allEchartDataRanking.num?.map(item => {
                        return {
                            name: item?.lineName || '',
                            data: item?.data || [],
                        }
                    })
                });
                return;
            }
            if (selectType === '增长人数') {
                setMockChartData(() => {
                    return allEchartDataRanking?.incr?.map(item => {
                        return {
                            name: item?.lineName || '',
                            data: item?.data || [],
                        }
                    })
                });
                return;
            }
            if (selectType === '增幅') {
                setMockChartData(() => {
                    return allEchartDataRanking?.rate?.map(item => {
                        return {
                            name: item?.lineName || '',
                            data: item?.data || [],
                        }
                    })
                });
                return;
            }
        }

    }, [selectType]);

    useEffect(() => {
        if (!echartXData.length) {
            return;
        }
        if (chartRef.current) {
            // 初始化图表
            chartInstance = echarts.init(chartRef.current);

            // 设置配置项
            const option = {
                // dataZoom: [
                //     {
                //         type: 'slider', // 滑动条型数据区域缩放组件
                //         show: true,
                //         start: 0, // 初始起点
                //         end: 30, // 初始终点
                //         handleSize: 8,
                //         xAxisIndex: [0]
                //     },
                // ],
                title: {
                    // 添加标题配置
                    text: `${subtitle}${subjectName}*对比考试排名情况分析-图表`,
                    left: 'center',
                    top: 0,
                    textStyle: {
                        fontSize: 16,
                        fontWeight: 'bold',
                    },
                },
                axisLabel: {
                    rotate: 35,
                    interval: 0,
                    fontSize: 9,
                    autoSkip: true,
                },
                barGap: '10%',
                barWidth: "10%",
                xAxis: {
                    name: '考试',
                    type: 'category',
                    axisTick: { show: false },
                    data: echartXData,
                    axisLabel: {
                        rotate: echartXData?.length > 6 ? 45 : 0,
                        interval: 0,
                        textStyle: {
                            fontSize: 10,
                        }
                    },
                    nameTextStyle: {
                        fontSize: 16,
                    }
                },
                grid: {
                    containLabel: true,
                    top: "20%"
                },
                yAxis: {
                    name: "",
                    axisLabel: {
                        textStyle: {
                            fontSize: 16,
                        }
                    },
                    nameTextStyle: {
                        fontSize: 16,
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                legend: {
                    type: "scroll",
                    data: tags,
                    right: 10, // 设置右侧边距
                    top: 16, // 设置顶部边距
                    selectedMode: false,
                    textStyle: {
                        fontSize: 12
                    }
                },
                series: intersectionData.map((item) => ({
                    ...commonSeries,
                    name: item?.name || '',
                    data: item?.data || [],

                }))
            };

            chartInstance.setOption(option);

            // 响应式调整
            const resizeHandler = () => chartInstance?.resize();
            window.addEventListener('resize', resizeHandler);

            // 清理函数
            return () => {
                window.removeEventListener('resize', resizeHandler);
                chartInstance?.dispose();
            };
        }
    }, [selectedTags, echartXData, mockChartData]);



    const init = async () => {
        setLoading(true);
        try {
            const res = await getExamRanking({
                examId,
                examIds: examList.map(item => item.id),
                limit: examSelectSort,
                subjectId: subjectId,
                schools: schoolIds
            });
            if (res.code === 200) {
                setResponseData(res);
                setLoading(false);
                setDataSource(res?.data || []);
                setExpandedRowKeys([res?.data?.[0]?.id, res?.data?.[0]?.children?.[0]?.id]);
                setTags(res?.columnDiagramResult?.num?.map(item => item?.lineName) || []);
                setSelectedTags([res?.columnDiagramResult?.num?.[0]?.lineName || '']);
                setTypeList(['人数', '增长人数', '增幅']);
                setSelectType('人数');
                setEchartXData(res?.columnDiagramResult?.num?.[0]?.xdata || []);
                setAllEchartDataRanking(res?.columnDiagramResult);
                setMockChartData(() => {

                    return res?.columnDiagramResult?.num?.map(item => {
                        return {
                            name: item?.lineName || '',
                            data: item?.data || [],
                        }
                    })
                });
                setColumns(() => {
                    return res?.columns?.map(item => {
                        return {
                            title: item?.label,
                            dataIndex: item?.prop,
                            align: "center",
                            width: item.label === "考试人数" ? 80 : item?.label === "区县" ? 300 : 240,
                            children: item?.children?.map(element => {
                                if (element?.label === '人数') {
                                    return {
                                        title: element?.label,
                                        dataIndex: element?.prop,
                                        align: "center",
                                        width: 120,
                                        render: (text) => (
                                            <Button type="link" style={{ color: "#4ABB6A" }} onClick={() => {
                                                const examId = element?.prop?.split('-')[1];
                                                setTitle(text?.typeDisc);
                                                studentGroupRef.current?.openModal();
                                                setStudentGroupParams({
                                                    examId,
                                                    students: text?.data
                                                });

                                            }}>{text?.value}</Button>
                                        ),
                                    }
                                }
                                return {
                                    title: element?.label,
                                    dataIndex: element?.prop,
                                    align: "center",
                                    width: 120,
                                    sorter: (a, b) => a[element?.prop] - b[element?.prop],
                                }
                            })

                        }
                    })
                })
                return;
            }
            setLoading(false);

        } catch (error) {
            setLoading(false);
            console.log(error, 'exam-ranking-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 getSortInit = async () => {
        try {
            const res = await getSort();
            if (res?.code === 200) {
                setExamSortList(res?.data || []);
                setExamSelectSort(res?.data?.[0]?.value);

            }

        } catch (error) {
            console.log(error, 'get-sort-init-error');

        }
    };


    const handleTagClick = (tag) => {
        if (selectedTags.includes(tag)) {
            // 如果 Tag 已经选中，则移除
            setSelectedTags((prev) => {
                if (prev.length === 1) {
                    return prev;
                }
                return selectedTags.filter((item) => item !== tag)
            });


        } else {
            // 如果 Tag 未选中，则添加
            setSelectedTags([...selectedTags, tag]);
        }

    };



    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 exportChart = (ref) => {
        const instance = echarts.getInstanceByDom(ref?.current);
        if (instance) {
            const base64 = instance?.getDataURL({
                type: "png",
                pixelRatio: 2, // 导出的图片分辨率比例
                backgroundColor: "#fff", // 导出图片的背景色
            });

            setEchartImg(base64);
        }
    };

    //下载图片
    const downloadImg = () => {
        const link = document.createElement("a");
        link.download = `图表_${new Date().getTime()}.png`;
        link.href = echartImg;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        setEchartImg("");
    };

    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));
            }
        },
    };



    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={navIconSrc} 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={() => {
                        exportChart(chartRef)
                    }}>导出图表</Button>)}
                </section>
                <Space style={{ marginBottom: 8 }}>
                    {examSortList.length > 0 ? (
                        examSortList.map((item, index) => {
                            const isSelected = item?.value === examSelectSort;
                            return (
                                <Tag
                                    onClick={() => setExamSelectSort(item?.value)}
                                    color={isSelected ? 'green' : 'default'}
                                    key={index}
                                    style={{
                                        cursor: 'pointer',
                                    }}
                                >
                                    {item?.label}
                                </Tag>
                            );
                        })
                    ) : null}
                </Space>
                <section>
                    <Space >
                        {typeList.length > 0 ? (
                            typeList.map((item, index) => {
                                const isSelected = selectType === item;
                                return (
                                    <Tag
                                        onClick={() => setSelectType(item)}
                                        color={isSelected ? 'green' : 'default'}
                                        key={index}
                                        style={{
                                            cursor: 'pointer',
                                        }}
                                    >
                                        {item}
                                    </Tag>
                                );
                            })
                        ) : null}
                    </Space>
                </section>
                <section style={{ marginTop: 8 }}>

                    <Space >
                        {tags.length > 0 ? (
                            tags.map((item, index) => {
                                const isSelected = selectedTags.includes(item);
                                return (
                                    <Tag
                                        onClick={() => handleTagClick(item)}
                                        color={isSelected ? 'green' : 'default'}
                                        key={index}
                                        style={{
                                            cursor: 'pointer',
                                        }}
                                    >
                                        {item}
                                    </Tag>
                                );
                            })
                        ) : null}
                    </Space>
                </section>
                <section className={styles.analysis_content_chart_content} >
                    <Spin spinning={loading} tip='计算中，请稍后'>
                        <div ref={chartRef} style={{ width: '100%', height: '460px' }}></div>
                    </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={navIconSrc} 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>
                    <Space >
                        {examSortList.length > 0 ? (
                            examSortList.map((item, index) => {
                                const isSelected = item?.value === examSelectSort;
                                return (
                                    <Tag
                                        onClick={() => setExamSelectSort(item?.value)}
                                        color={isSelected ? 'green' : 'default'}
                                        key={index}
                                        style={{
                                            cursor: 'pointer',
                                        }}
                                    >
                                        {item?.label}
                                    </Tag>
                                );
                            })
                        ) : null}
                    </Space>
                </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}
            />
            {echartImg && (
                <Modal
                    title="导出图表"
                    width={'80vw'}
                    className="custom-modal"
                    open={true}
                    okText="下载"
                    onCancel={() => {
                        setEchartImg("");
                    }}
                    onOk={downloadImg}
                >
                    <Flex style={{ height: "100%" }} alignItems="center" justify="center">
                        <Image src={echartImg} width={"100%"} />
                    </Flex>
                </Modal>
            )}
        </div>
    )

};

export default ContrastExamRanking;