import { useState, useEffect, useRef } from 'react';
import { Space, Select, Button, Spin, Empty, Table, InputNumber, message, Tag } from 'antd';
import { getOnlineAnalysis } from '@/apis/leader';
import { getSubjectListAll } from '@/apis/common';
import SchoolChoice from '@/components/SchoolChoice';
import ScoreLineSelect from '@/components/ScoreLineSelect';
import Echarts from "@/components/Echarts";
import StudentGroup from '@/components/StudentGroup';
import { tableCommonProps } from '@/utils/config.js';
import { downloadTableData } from '@/apis/download';
import { getScoreLineList } from '@/apis/data';
import { getSubjectList } from '@/apis/subject';
import { downloadExcelFile } from '@/utils/file';
import { buildEchartData, removeEmptyChildren } from '@/utils/table';
// import useSchool from '@/stores/useSchool';
import sectionSrc1 from '@/assets/icon/analysis-catalogue-1.png';
import styles from './index.less';

const OnlineSituation = (props) => {

    const { examId = '', subtitle = '', isShowChart = false, isShowTable = false, idx = '', actionShow = true } = props;
    // const { school } = useSchool();
    const [dataSource, setDataSource] = useState([]);
    const [columns, setColumns] = useState([]);
    const [responseData, setResponseData] = useState({});
    const [scoreList, setScoreList] = 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 studentGroupRef = useRef();
    const [title, setTitle] = useState('');
    const [studentGroupParams, setStudentGroupParams] = useState({});

    const [allSubjectList, setAllSubjectList] = useState([]);

    const [rankingList, setRankingList] = useState([]);
    const [selectRaking, setSelectRaking] = useState('');

    const [tagList, setTagList] = useState([]);
    const [selectTag, setSelectTag] = useState('');
    const [allEchartData, setAllEchartData] = useState({});
    const [selectValues, setSelectValues] = useState([]);
    const [subjectOptions, setSubjectOptions] = useState([]);
    const [scoreLine, setScoreLine] = useState([]);
    const [score, setScore] = useState(null);
    const [scoreLineList, setScoreLineList] = useState([]);
    const [loading2, setLoading2] = useState(false);
    const [subjectIds, setSubjectIds] = useState([]);

    const [scoreLine2, setScoreLine2] = 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(() => {
        // allSubjectInit();
        getSubjectSelectOptions();

    }, []);

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


    useEffect(() => {

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



    }, [examId, schoolIds, scoreLine]);

    useEffect(() => {

        if (!examId) {
            return;
        }

        chartInit();

    }, [examId, schoolIds, scoreLine, scoreLine2]);


    useEffect(() => {

        if (selectTag === "上线人数") {

            const data = buildEchartData(allEchartData?.num);
            setEchartData(data);
            setLengButton(allEchartData?.num?.map(item => item?.lineName));

        }
        if (selectTag === "上线率") {
            const data = buildEchartData(allEchartData?.incr);
            setEchartData(data);
            setLengButton(allEchartData?.incr?.map(item => item?.lineName));
        }

    }, [selectTag])

    const init = async () => {
        try {
            setLoading(true);
            const res = await getOnlineAnalysis({
                examId,
                scoreLines: scoreLine,
                lineId: '',
                schools: schoolIds,
            });
            if (res?.code === 200) {
                setResponseData(res);
                setLoading(false);
                const list = removeEmptyChildren(res.data);
                setDataSource(list);

                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: 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={() => {
                                                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],
                                }
                            })

                        }
                    })

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

        }
    };

    const chartInit = async () => {
        try {
            setLoading2(true);
            const res = await getOnlineAnalysis({
                examId,
                scoreLines: scoreLine?.length > 0 ? scoreLine : scoreLine2,
                lineId: selectRaking,
                schools: schoolIds,
            });
            if (res?.code === 200) {
                setLoading2(false);
                setTagList(['上线人数', '上线率']);
                setSelectTag('上线人数');
                const data = buildEchartData(res?.columnDiagramResult?.num);

                setEchartData(data);
                setLengButton(res?.columnDiagramResult?.num?.map(item => item?.lineName));
                setAllEchartData(res?.columnDiagramResult);
            }
            setLoading2(false);
        } catch (error) {
            setLoading2(false);
            console.log(error, 'init-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 getSubjectSelectOptions = async () => {
        try {
            const res = await getSubjectList({ stages: 3, contain256: false, level: 1, single: true, showFlag: true });
            if (res?.code === 200) {

                setSelectValues(() => {
                    return res?.data?.map(item => {
                        return {
                            label: item?.cname,
                            value: item?.id
                        }
                    })
                })
            }
        } catch (error) {
            console.log(error, 'getSubjectSelectOptions-error');

        }
    };

    const getSortInit = async () => {
        try {
            const res = await getScoreLineList({ stage: 3, examId, });
            if (res?.code === 200) {
                const list = res?.data?.map(item => ({
                    id: item?.id,
                    score: item?.score,
                    name: item?.name,
                    combIds: item?.combIds,
                }));
                setRankingList(list);
                setScoreLine2([list?.[0]]);

            }

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

        }
    };

    const handleDownload = async () => {
        try {
            const res = await downloadTableData(responseData);
            if (res?.status === 200) {
                downloadExcelFile(res, `${subtitle}${scoreLineList?.length > 0 ? scoreLine?.map(item => item?.name)?.join(',') : scoreLine2?.map(item => item?.name)?.join(',')}`);
            }

        } 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={sectionSrc1} className={styles.page_title_img} />
                        <span className={styles.page_title_text}>{subtitle}上线情况分析-图表</span>
                        <Space>
                            <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}>
                    <section style={{ display: "flex", alignItems: "center" }}>
                        <span style={{ color: " #8a8a8a" }}>设置选科范围：</span>
                        <Select style={{ width: 260 }} maxTagCount={2} placeholder='请选择学科' value={subjectIds} mode='multiple' allowClear options={selectValues} onChange={(value, options) => {
                            if (!value.length) {
                                setSubjectIds([]);
                                setSubjectOptions([]);
                                return;
                            }
                            setSubjectIds(value);
                            setSubjectOptions(options);

                        }} />
                    </section>
                    <section style={{ display: "flex", alignItems: "center", marginTop: 16 }}>
                        <span style={{ color: " #8a8a8a" }}>设置分数线：</span>
                        <InputNumber
                            min={1}
                            value={score}
                            onChange={(value) => setScore(value)}
                            style={{ width: 120 }}
                        />
                        &nbsp;&nbsp;分以上&nbsp;&nbsp;
                        <Button onClick={() => {
                            if (typeof score !== 'number') {
                                message.error('请输入数字');
                                return;
                            }

                            const item = {
                                score,
                                name: !!subjectOptions?.length ? `总分${score}以上，选${subjectOptions?.map(item => item?.label).join('，')}` : `总分${score}以上`,
                                combIds: subjectIds?.join(',')
                            };
                            if (scoreLineList?.map(item => item?.name).includes(item.name)) {
                                message.error('该分数线已存在，勿重新添加');
                                return;
                            }
                            setScoreLine((prev) => {
                                return [...prev, item]
                            })
                            setScoreLineList((prev) => {
                                return [...prev, item];
                            })
                            setScore(null);
                        }}>
                            确定
                        </Button>
                    </section>
                    <section style={{ marginTop: 16 }}>
                        {scoreLineList?.length ? (
                            <Space>
                                {scoreLineList?.map((item, index) => {
                                    const isSelected = scoreLine?.map(i => i?.name)?.includes(item?.name);
                                    return (<Tag
                                        key={index}
                                        color={isSelected ? "green" : "default"}
                                        closable
                                        style={{ cursor: 'pointer' }}
                                        onClick={() => {

                                            if (scoreLine?.map(element => element?.name)?.includes(item?.name)) {
                                                // 如果 Tag 已经选中，则移除
                                                setScoreLine((prev) => {
                                                    if (prev.length === 1) {
                                                        return prev;
                                                    }
                                                    return scoreLine.filter((element) => element?.name !== item?.name)
                                                });


                                            } else {
                                                // 如果 Tag 未选中，则添加
                                                setScoreLine([...scoreLine, item]);
                                            }

                                        }}
                                        onClose={() => {
                                            setScoreLine(scoreLine.filter((element) => element?.combIds !== item?.combIds));
                                            setScoreLineList(scoreLineList.filter(i => i?.name !== item?.name))
                                        }}
                                    >
                                        {item?.name}
                                    </Tag>);
                                })}
                            </Space>

                        ) : null}
                    </section>
                    {!scoreLineList?.length ? (
                        <Space style={{ marginBottom: 16 }} wrap>
                            {rankingList.length > 0 ? (
                                rankingList.map((item, index) => {
                                    const isSelected = scoreLine2?.map(i => i?.id)?.includes(item?.id);
                                    return (
                                        <Tag
                                            onClick={() => {


                                                if (scoreLine2?.map(element => element?.id)?.includes(item?.id)) {
                                                    // 如果 Tag 已经选中，则移除
                                                    setScoreLine2((prev) => {
                                                        if (prev.length === 1) {
                                                            return prev;
                                                        }
                                                        return scoreLine2.filter((element) => element?.id !== item?.id)
                                                    });


                                                } else {
                                                    // 如果 Tag 未选中，则添加
                                                    setScoreLine2([...scoreLine2, item]);
                                                }
                                            }}
                                            color={isSelected ? 'green' : 'default'}
                                            key={index}
                                            style={{
                                                cursor: 'pointer',
                                            }}
                                        >
                                            {item?.name}
                                        </Tag>
                                    );
                                })
                            ) : null}
                        </Space>
                    ) : null}
                    <section style={{ marginTop: 8 }}>
                        {tagList?.length ? (
                            <Space wrap>
                                {tagList.length > 0 ? (
                                    tagList.map((item, index) => {
                                        const isSelected = selectTag === item;
                                        return (
                                            <Tag
                                                onClick={() => setSelectTag(item)}
                                                color={isSelected ? 'green' : 'default'}
                                                key={index}
                                                style={{
                                                    cursor: 'pointer',
                                                }}
                                            >
                                                {item}
                                            </Tag>
                                        );
                                    })
                                ) : null}
                            </Space>
                        ) : null}
                    </section>
                    <Spin spinning={loading2} tip='计算中，请稍后'>
                        {lengButton?.length > 0 ? (<Echarts
                            ref={echartRef}
                            hasTable={false}
                            hasExport={false}
                            data={echartData}
                            type={"bar"}
                            isShow={true}
                            isNoneTag={true}
                            isShowTag={false}
                            text={`${subtitle}${scoreLineList?.length > 0 ? scoreLine?.map(item => item?.name)?.join(',') : scoreLine2?.map(item => item?.name)?.join(',')}`}
                            lengButton={lengButton}

                        />) : <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={sectionSrc1} 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 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}
            />
        </div>
    )
};


export default OnlineSituation;