import { useState, useEffect, useRef } from 'react';
import { Space, Button, Spin, Table, Tag } from 'antd';
import { getSelectedDistribution } from '@/apis/leader';
import { getNoSingleCombine } 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 ChoiceExamAnalysis = (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 [echartData, setEchartData] = useState({});
    const [lengButton, setLengButton] = useState([]);
    const echartRef = useRef();

    const [subjectId, setSubjectId] = useState('');
    const [tags, setTags] = useState([]);
    const [selectedTag, setSelectedTag] = 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(() => {
        getNoSingleCombineInit();
    }, [])


    useEffect(() => {

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

    }, [examId, schoolIds,subjectId]);


    const init = async () => {
        setLoading(true);
        try {
            const res = await getSelectedDistribution({
                examId,
                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",
                            sorter: item?.sortable ? (a, b) => a[item?.prop] - b[item?.prop] : false
                        }
                    })
                });
                if (!res?.columnDiagramResult?.avg?.length) {
                    return;
                }
                setLengButton(res?.columnDiagramResult?.avg?.map(item => item?.lineName));
                setEchartData(() => {
                    return {
                        xAxis: {
                            name: "",
                            type: "category",
                            axisTick: { show: false },
                            data: res?.columnDiagramResult?.avg?.[0]?.xdata,
                        },
                        yAxis: {
                            name: '',
                        },
                        tooltip: {
                            show: true,
                        },
                        yChartData: res?.columnDiagramResult?.avg?.map(item => {
                            return {
                                name: item?.lineName,
                                data: item?.data
                            }
                        })
                    }
                });
            }
            setLoading(false);
        } catch (error) {
            setLoading(false);
            console.log(error, 'paramsInit-error');

        }
    };

    const getNoSingleCombineInit = async () => {
        try {
            const list = await getNoSingleCombine();
            if (list?.code === 200) {
                setTags(list?.data || []);
                setSelectedTag(list.data?.[0]?.cname || '');
                setSubjectId(list.data?.[0]?.id || '');

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

        }
    }

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

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

        }
    };


    const handleNavTagClick = (tag) => {
        setSelectedTag(tag?.cname || '');
        setSubjectId(tag?.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={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}}>
                            {tags.length > 0 ? (
                                tags.map((item, index) => {
                                    const isSelected = selectedTag === item?.cname;
                                    return (
                                        <Tag
                                            onClick={() => handleNavTagClick(item)}
                                            color={isSelected ? 'green' : 'default'}
                                            key={index}
                                            style={{
                                                cursor: 'pointer',
                                            }}
                                        >
                                            {item?.cname}
                                        </Tag>
                                    );
                                })
                            ) : null}
                        </Space>
                        <Spin spinning={loading} tip='计算中，请稍后'>
                            <Echarts
                                data={echartData}
                                text={`考试选考组合分析*${subtitle}*${selectedTag}`}
                                type={"bar"}
                                lengButton={lengButton}
                                ref={echartRef}
                                hasTable={false}
                                hasExport={false}
                            />
                        </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}>
                        <Space  style={{marginBottom:8}}>
                            {tags.length > 0 ? (
                                tags.map((item, index) => {
                                    const isSelected = selectedTag === item?.cname;
                                    return (
                                        <Tag
                                            onClick={() => handleNavTagClick(item)}
                                            color={isSelected ? 'green' : 'default'}
                                            key={index}
                                            style={{
                                                cursor: 'pointer',
                                            }}
                                        >
                                            {item?.cname}
                                        </Tag>
                                    );
                                })
                            ) : null}
                        </Space>
                        <Table
                            {...tableCommonProps}
                            dataSource={dataSource}
                            columns={columns}
                            locale={{ emptyText: loading ? "计算中，请稍后" : "暂无数据" }}
                            loading={{ spinning: loading, tip: "计算中，请稍后" }}
                            expandable={expandableConfig}
                        >
                        </Table>
                    </section>
                </section>
            ) : null}
        </div>
    );
};

export default ChoiceExamAnalysis;