import { useRef, useEffect, useState, useMemo } from 'react';
import * as echarts from 'echarts';
import { Space, Tag, Button, Image, Modal, Table, Spin } from 'antd';
import Flex from "@/components/Flex";
import StudentGroup from '@/components/StudentGroup';
import ScreenPage from "@/components/ScreenPage";
import StudentModal from "@/pages/report/components/StudentModal";
import { studentData, studentCol } from "@/pages/mock/tableData";
import { getParamsRanking } from '@/apis/exam';
import { getExam, getParamsType, getPercent, getSort } from '@/apis/common';
import upSrc from "@/assets/image/up.png";
import downSrc from "@/assets/image/down.png";
import Common from "@/utils/Common";
import styles from './index.less';
import { downloadTableData } from '@/apis/download';
import { downloadExcelFile } from '@/utils/file';

const PercentageComparisonPage = () => {

    const [visibleModal, setVisibleModal] = useState(false);
    const [isShow1, setIsShow1] = useState(false);
    const [isShow2, setIsShow2] = useState(false);
    const [open, setOpen] = useState(1);
    const [isDx, setisDx] = useState(true);
    const [expandedRowKeys, setExpandedRowKeys] = useState([]);

    const [selectedNavTag, setSelectedNavTag] = useState('');
    const [selectedNavTag2, setSelectedNavTag2] = useState('');

    const handleExpand = (expanded, record) => {
        if (expanded) {
            setExpandedRowKeys([...expandedRowKeys, record.id]);
        } else {
            setExpandedRowKeys(expandedRowKeys.filter((k) => k !== record.id));
        }
    };


    const [subtitle, setSubtitle] = useState('');
    const [params, setParams] = useState({});
    const [dataSource, setDataSource] = useState([]);
    const [columns, setColumns] = useState([]);
    const [loading, setLoading] = useState(false);
    const [examList, setExamList] = useState([]);
    const [limit, setLimit] = useState();


    const [rateList, setRateList] = useState([]);
    const [rate, setRate] = useState();

    const [paramsTypeList, setParamsTypeList] = useState([]);
    const [paramsType, setParamsType] = useState();

    let chartInstance = null;
    const [tags, setTags] = useState([]);
    const [echartImg, setEchartImg] = useState();
    const chartRef = useRef(null);
    const [selectedTags, setSelectedTags] = useState('');
    const [echartXData, setEchartXData] = useState([]);
    const [mockChartData, setMockChartData] = useState([]);


    const [chartTagList, setChartTagList] = useState([]);
    const [chartTag, setChartTag] = useState('');

    const [type, setType] = useState();

    const [spin, setSpin] = useState(false);

    const [rankingList, setRankingList] = useState([]);
    const [selectRaking, setSelectRaking] = useState();
    const [selectRaking2, setSelectRaking2] = useState();
    const [limit2, setLimit2] = useState();

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

    const [typeList,setTypeList] = useState([]);
    const [selectType,setSelectType] = useState('');

    const [allEchartData,setAllEchartData] = useState({});

    const [responseData,setResponseData] = useState({});




    useEffect(() => {
            if(selectType){
                if(selectType === chartTag){
                    setMockChartData(()=>{
                        return allEchartData.num?.map(item=>{
                            return {
                                name: item?.lineName || '',
                                data: item?.data || [],
                            }
                        })
                    });
                    return;
                }
                if(selectType === `${chartTag}增长`){
                    setMockChartData(()=>{
                        return allEchartData?.incr?.map(item=>{
                            return {
                                name: item?.lineName || '',
                                data: item?.data || [],
                            }
                        })
                    });
                    return;
                }
                if(selectType === '增幅'){
                    setMockChartData(()=>{
                        return allEchartData?.rate?.map(item=>{
                            return {
                                name: item?.lineName || '',
                                data: item?.data || [],
                            }
                        })
                    });
                    return;
                }
            }
    
        }, [selectType]);
    useEffect(() => {
        if (!Object.values(params).length > 0) {
            return;
        }
        init();

    }, [params?.examId, params?.subjectId, params?.schools, examList, limit2, paramsType]);


    useEffect(() => {
        paramsTypeInit();
        percentInit();
        sortInit();
    }, []);

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


    useEffect(() => {
        if (type) {
            charInit();
        }

    }, [params?.examId, params?.subjectId, params?.schools, examList, limit, type]);

    const charInit = async () => {
        setSpin(true);
        try {
            const res = await getParamsRanking({
                ...params,
                examIds: examList.map(item => item.id),
                limit,
                type,

            });
            if (res.code === 200) {
                setSpin(false);
                if (Object.values(res?.columnDiagramResult)?.length) {
                    console.log(res?.columnDiagramResult,'图表数据');
                    setAllEchartData(res?.columnDiagramResult);
                    setTypeList([chartTag,`${chartTag}增长`,'增幅']);
                    setSelectType(chartTag);
                    setTags(res?.columnDiagramResult?.num?.map(item => item?.lineName));
                    setSelectedTags(res?.columnDiagramResult?.num?.[0]?.lineName || '');
                    setEchartXData(res?.columnDiagramResult?.num?.[0]?.xdata);

                    setMockChartData(() => {

                        return res?.columnDiagramResult?.num?.map(item => {
                            return {
                                name: item?.lineName,
                                data: item?.data,
                            }
                        });
                    });
                }
            }
        } catch (error) {
            setSpin(false);
            console.log(error, 'exam-ranking-error');
        }
    }

    const init = async () => {
        setLoading(true);
        try {
            const res = await getParamsRanking({
                ...params,
                examIds: examList.map(item => item.id),
                limit: limit2,
                type: paramsType

            });

            if (res.code === 200) {
                setLoading(false);
                setResponseData(res);
                setDataSource(res?.data || []);
                setExpandedRowKeys([res?.data?.[0]?.id,res?.data?.[0]?.children?.[0]?.id]);
                setColumns(() => {
                    return res?.columns?.map(item => {
                        return {
                            title: item?.label,
                            dataIndex: item?.prop,
                            align: "center",
                            width: ['区县', '平均分']?.includes(item?.label) ? 200 : 300,
                            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 paramsTypeInit = async () => {
        try {
            const params = await getParamsType();
            if (params.code === 200) {
                setParamsTypeList(params?.data || []);
                setParamsType(params?.data?.[0]?.value || '');
                setSelectedNavTag(params?.data?.[0]?.label || '');
                setChartTagList(params?.data || []);
                setChartTag(params?.data?.[0]?.label || '');
                setType(params?.data?.[0]?.value || '')

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

    const percentInit = async () => {
        try {
            const percent = await getPercent();
            if (percent.code === 200) {
                setRateList(percent?.data || []);
                setRate(percent?.data?.[0]?.value || '');
                setSelectedNavTag2(percent?.data?.[0]?.label || '')
            }
        } catch (error) {
            console.log(error, 'percent-init-error');

        }
    };

    const sortInit = async () => {
        try {
            const res = await getSort();
            if (res?.code === 200) {
                setSelectRaking(999999);
                setLimit(999999);
                setSelectRaking2(999999);
                setLimit2(999999);
                setRankingList(() => {
                    return [{ label: "全部", value: 999999 }, ...res?.data];
                });
            }

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

        }
    };

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


    const commonSeries = {
        type: 'line',
        barGap: 0,
        label: labelOption,
        emphasis: {
            focus: 'series'
        },
    };
    const handleNavTagClick = (tag) => {
        setSelectedNavTag(tag?.label || '');
        setParamsType(tag?.value || '');

    };

    const handleNavTagClick2 = (tag) => {
        setSelectedNavTag2(tag?.label || '');
        setRate(tag?.value || '');

    };

    const handleNavTagClick3 = (tag) => {
        setChartTag(tag?.label || '');
        setType(tag?.value || '');

    };

    const handleTagClick = (tag) => {
        // setSelectedTags(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 handleRakingClick = (item) => {
        setSelectRaking(item?.value);
        setLimit(item?.value);

    };

    const handleRakingClick2 = (item) => {
        setSelectRaking2(item?.value);
        setLimit2(item?.value);

    };

    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}*对比考试参数分析`,
                    left: 'center',
                    top: 0,
                    textStyle: {
                        fontSize: 16,
                        fontWeight: 'bold',
                    },
                },
                axisLabel: {
                    rotate: 35,
                    interval: 0,
                    fontSize: 9,
                    autoSkip: true,
                },
                xAxis: {
                    name: '考试',
                    type: 'category',
                    axisTick: { show: false },
                    data: echartXData,
                    axisLabel: {
                        rotate: echartXData.length > 6 ? 45 : 0,
                        interval: 0,
                        textStyle: {
                            fontSize: 12,
                        }
                    },
                    nameTextStyle: {
                        fontSize: 16,
                    }
                },
                yAxis: {
                    name: "",
                    axisLabel: {
                        textStyle: {
                            fontSize: 10,
                        }
                    },
                    nameTextStyle: {
                        fontSize: 16,
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                legend: {
                    type: "scroll",
                    data: tags,
                    selectedMode: false,
                    right: 10, // 设置右侧边距
                    top: 24, // 设置顶部边距
                    textStyle: {
                        fontSize: 12
                    }
                },
                grid: {
                    containLabel: true,
                    top: '20%',
                },
                barGap: '10%',
                barWidth: "10%",
                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 exportChart = () => {
        const chartInstance = echarts.getInstanceByDom(chartRef.current);
        if (chartInstance) {
            const base64 = chartInstance.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 handleDownload = async () => {
        try {
            const res = await downloadTableData(responseData);
            if (res?.status === 200) {
                downloadExcelFile(res, `${subtitle}*对比考试参数分析`);
            }

        } catch (error) {
            console.log(error, 'download-error');

        }
    };

    return (
        <div className={styles.params}>
            <div style={{ display: (isShow1 && !isShow2) ? 'block' : 'none' }}>
                <ScreenPage
                    isShow={isShow1}
                    isSingle={true}
                    isShowSubject={true}
                    onChange={(e) => {
                        setSubtitle([e?.currentSchool?.[0]?.districtName || e?.currentSchool?.[0]?.cname,e?.currentGrade?.[0]?.name, e?.currentSemester?.[0]?.name, e?.currentExamination?.[0]?.name,e?.currentDiscipline?.[0]?.name].filter(item => !!item).join("*"));
                        setParams({
                            examId: e?.examId,
                            schools: e?.currentSchool?.[0]?.schoolList?.map(item => item?.id) || e?.currentSchool?.map(item => item?.id),
                            subjectId: e?.currentDiscipline?.[0]?.id || '',
                        });
                    }}
                    saveshow={(e) => {
                        setIsShow1(e);
                    }}
                />
            </div>

            <div style={{ display: (isShow2 && !isShow1) ? 'block' : 'none' }}>
                <ScreenPage
                    isShow={isShow2}
                    isSingle={false}
                    isShowSubject={false}
                    isShowSchool={false}
                    onChange={(e) => {
                        const term = e?.currentGrade?.map(item => item?.name);
                        const semester = e?.currentSemester?.map(item => item?.name);
                        const examName = e?.currentExamination?.map(item => item?.name);
                        getExam({
                            term,
                            semester,
                            examName,
                        }).then(res => {
                            if (res.code === 200) {
                                setExamList(res.data || []);
                            }

                        }).catch(error => {
                            console.log(error, 'get-exam-error');

                        })
                    }}
                    saveshow={(e) => {
                        setIsShow2(e);
                    }}
                />
            </div>
            <section className={styles.params_table}>
                <Space>
                    <span style={{ fontSize: 16, fontWeight: "bold" }}>对比考试参数分析</span>
                    {/* <Select
                        placeholder="总分"
                        style={{ marginLeft: 12, width: 140 }}
                        options={mockScoreSelectData}
                        onChange={(value)=>{
                            setScoreValue(value);
                        }}
                    /> */}
                </Space>
                <Flex
                    style={{
                        display: "flex",
                        alignItems: "center",
                        margin: "5px 0",
                        gap: 12,
                    }}
                    alignItems="center"
                >
                    <Flex alignItems="center">
                        <Flex
                            style={{
                                display: "flex",
                                alignItems: "center",
                                color: "#8a8a8a",
                            }}
                        >
                            {" "}
                            当前考试 : &nbsp;
                            <h3
                                style={{
                                    color: "black",
                                }}
                            >
                                {subtitle}
                            </h3>
                        </Flex>
                    </Flex>

                    <Flex
                        style={{
                            padding: "4px 8px",
                            border: "1px solid #666",
                            borderRadius: 5,
                            cursor: "pointer",
                            marginLeft: 10,
                        }}
                        alignItems="center"
                        onClick={() => {
                            setIsShow1(!isShow1);
                            setIsShow2(false);
                        }}
                    >
                        选择考试和学校
                        <img
                            src={isShow1 ? upSrc : downSrc}
                            width={14}
                            height={12}
                            style={{ marginLeft: 5 }}
                        />
                    </Flex>
                </Flex>
                <section className={styles.select}>
                    <div className={styles.select_title}>对比考试: &nbsp;</div>
                    <section className={styles.select_content}>
                        {examList?.filter(item => item?.id !== params?.examId)?.map((item) => {
                            return (
                                <Tag
                                    key={item.id}
                                    // onClose={(e) => {
                                    //     e.preventDefault();
                                    //     setExamList((prev) => {
                                    //         return prev.filter((i) => i?.id !== item?.id)
                                    //     });
                                    // }}
                                    // closeIcon
                                    style={{
                                        color: "black",
                                        fontWeight: "bold",
                                        fontSize: 14,
                                        marginTop: 4,
                                        height:24
                                    }}
                                >
                                    {`${item?.term}*${item?.semester}*${item?.examName}`}
                                </Tag>
                            );
                        })}
                        <div
                            className={styles.select_action}
                            style={{width:100}}
                            onClick={() => {
                                setIsShow2(!isShow2);
                                setIsShow1(false);
                            }}
                        >
                            选择考试
                            <img
                                src={isShow2 ? upSrc : downSrc}
                                width={14}
                                height={12}
                                style={{ marginLeft: 5 }}
                            />

                        </div>
                    </section>
                </section>
                {/* <Flex
                    style={{
                        width: "100%",
                        display: "flex",
                        alignItems: "center",
                        margin: "5px 0",
                    }}
                    alignItems="center"
                >
                    <Flex alignItems="center">
                        <Flex alignItems="center"
                            style={{
                                width: "100%",
                                display: "flex",
                                alignItems: "center",
                                color: "#8a8a8a",
                            }}
                        >
                            对比考试 : &nbsp;
                            <Flex wrap="wrap" style={{width:"70%"}}>
                                {examList?.map((item) => {
                                    return (
                                        <Tag
                                            key={item.id}
                                            // onClose={(e) => {
                                            //     e.preventDefault();
                                            //     setExamList((prev) => {
                                            //         return prev.filter((i) => i?.id !== item?.id)
                                            //     });
                                            // }}
                                            // closeIcon
                                            style={{
                                                color: "black",
                                                fontWeight: "bold",
                                                fontSize: 14
                                            }}
                                        >
                                            {`${item?.term}*${item?.semester}*${item?.examName}`}
                                        </Tag>
                                    );
                                })}
                                
                            </Flex>
                        </Flex>
                    </Flex>
                    <Flex
                        style={{
                            padding: "4px 8px",
                            border: "1px solid #666",
                            borderRadius: 5,
                            cursor: "pointer",
                            marginLeft: 10,
                        }}
                        alignItems="center"
                        onClick={() => {
                            setIsShow2(!isShow2);
                            setIsShow1(false);
                        }}
                    >
                        选择考试和学校
                        <img
                            src={isShow2 ? upSrc : downSrc}
                            width={14}
                            height={12}
                            style={{ marginLeft: 5 }}
                        />
                    </Flex>
                </Flex> */}
                <section className={styles.params_charts_nav}>
                    <Space>
                        {rankingList.length > 0 ? (
                            rankingList.map((item, index) => {
                                const isSelected = selectRaking2 === item?.value;
                                return (
                                    <Tag
                                        onClick={() => handleRakingClick2(item)}
                                        color={isSelected ? 'green' : 'default'}
                                        key={index}
                                        style={{
                                            cursor: 'pointer',
                                        }}
                                    >
                                        {item?.label}
                                    </Tag>
                                );
                            })
                        ) : null}
                    </Space>
                    <Space>
                        {paramsTypeList.length > 0 ? (
                            paramsTypeList.map((item, index) => {
                                const isSelected = selectedNavTag === item?.label;
                                return (
                                    <Tag
                                        onClick={() => handleNavTagClick(item)}
                                        color={isSelected ? 'green' : 'default'}
                                        key={index}
                                        style={{
                                            cursor: 'pointer',
                                        }}
                                    >
                                        {item?.label}
                                    </Tag>
                                );
                            })
                        ) : null}
                    </Space>
                </section>
                <section>
                    <Table
                        bordered={true}
                        dataSource={dataSource}
                        columns={columns}
                        locale={{ emptyText: loading ? "计算中，请稍后" : "暂无数据" }}
                        loading={{ spinning: loading, tip: "计算中，请稍后" }}
                        scroll={{ x: 1400,y:340 }}
                        style={{maxHeight:460}}
                        pagination={false}
                        sticky={true}
                        rowKey="id"
                        expandable={{
                            expandedRowKeys,
                            onExpand: handleExpand,
                        }}
                    >

                    </Table>
                    

                </section>
                    <Button
                        type="primary"
                        style={{ marginTop: 24 }}
                        disabled={!dataSource?.length}
                        onClick={handleDownload}
                    >
                        导出表格
                    </Button>
            </section>
            <section className={styles.params_charts} style={{marginTop:16}}>

                <section className={styles.params_charts_nav}>

                    <Space>
                        {rankingList.length > 0 ? (
                            rankingList.map((item, index) => {
                                const isSelected = selectRaking === item?.value;
                                return (
                                    <Tag
                                        onClick={() => handleRakingClick(item)}
                                        color={isSelected ? 'green' : 'default'}
                                        key={index}
                                        style={{
                                            cursor: 'pointer',
                                        }}
                                    >
                                        {item?.label}
                                    </Tag>
                                );
                            })
                        ) : null}
                    </Space>

                    <Space style={{marginTop:8}}>
                        {chartTagList.length > 0 ? (
                            chartTagList.map((item, index) => {
                                const isSelected = chartTag === item?.label;
                                return (
                                    <Tag
                                        onClick={() => handleNavTagClick3(item)}
                                        color={isSelected ? 'green' : 'default'}
                                        key={index}
                                        style={{
                                            cursor: 'pointer',
                                        }}
                                    >
                                        {item?.label}
                                    </Tag>
                                );
                            })
                        ) : null}
                    </Space>
                    <Space style={{marginTop:8}}>
                        {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>
                    <Spin spinning={spin}>

                        <Space style={{marginTop:8}}>
                            {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>
                    </Spin>
                </section>
                <Spin spinning={spin} tip='计算中，请稍后'>
                    <div className={styles.params_charts_container} style={{marginTop:64}}>
                        <div ref={chartRef} style={{ width: '100%', height: '520px' }}></div>
                    </div>
                </Spin>

                <div className={styles.params_charts_action}>
                    <Button
                        type="primary"
                        style={{ marginRight: 20 }}
                        disabled={!mockChartData?.length}
                        onClick={exportChart}
                    >
                        导出图表
                    </Button>
                </div>
            </section>
            {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>
            )}
            {visibleModal && (
                <StudentModal
                    title="丽水中学1班学生群体"
                    studentData={studentData}
                    studentCol={studentCol}
                    closeModal={() => {
                        setVisibleModal(false);
                    }}
                />
            )}
            <StudentGroup
                ref={studentGroupRef}
                params={studentGroupParams}
                title={title}
            />
        </div>

    )
};

export default PercentageComparisonPage;