
import { useState, useEffect, useRef } from 'react';
import { Space, Select, Button, Spin, Empty, Table, Input } from 'antd';
import { getTopStudentAnalysis } from '@/apis/leader';
import { getSubjectListAll } from '@/apis/common';
import SchoolChoice from '@/components/SchoolChoice';
import Echarts2 from '@/pages/report/components/Echarts';
import StudentModal from '@/components/StudentModal';
import { tableCommonProps } from '@/utils/config.js';
import { downloadTableData } from '@/apis/download';
import { downloadExcelFile } from '@/utils/file';
import { buildBarAndPieOption } from '@/utils/table';
import sectionSrc from '@/assets/icon/analysis-catalogue-4.png';

import styles from './index.less';


const TopStudent = (props) => {



    const { examId = '', subtitle = '', isShowChart = false, isShowTable = false,idx = '',actionShow = true } = props;
    const [dataSource, setDataSource] = useState([]);
    const [columns, setColumns] = useState([]);
    const [responseData, setResponseData] = useState({});
    const [loading, setLoading] = useState(false);
    const [subjectId, setSubjectId] = useState("");
    const [subjectName, setSubjectName] = useState(null);
    const [schoolIds, setSchoolIds] = useState([]);
    const [echartData, setEchartData] = useState({});
    const [lengButton, setLengButton] = useState([]);
    const echartRef = useRef();

    const studentRef = useRef();
    const [studentParams, setStudentParams] = useState({});

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

    const [topStudentLimit, setTopStudentLimit] = useState(50);
    const timer = useRef(null);

    const [limit,setLimit] = useState(50);

    useEffect(() => {
        allSubjectInit();
        return () => {
            clearTimeout(timer.current);
        };
    }, []);
    useEffect(() => {

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

    }, [examId, schoolIds, subjectId, limit]);


    const init = async () => {

        try {
            setLoading(true);
            const res = await getTopStudentAnalysis({
                examId,
                subjectId: subjectId,
                limit,
                schools: schoolIds
            });
            if (res.code === 200) {
                setLoading(false);
                setResponseData(res);
                setLengButton([res?.columnDiagramResult?.rate?.[0]?.lineName, res?.columnDiagramResult?.num?.[0]?.lineName]);
                const option = buildBarAndPieOption(res?.columnDiagramResult);
                setEchartData(option);

                setDataSource(res?.data || []);
                setColumns(() => {
                    return res?.columns?.map(item => {
                        if (item?.label === '学生姓名') {
                            return {
                                title: item?.label,
                                dataIndex: item?.prop,
                                align: "center",
                                width: 120,
                                render: (value, record) => {


                                    return <Button type="link" onClick={() => {
                                        setStudentParams({
                                            studentName: record?.name,
                                            studentId: record?.studentId,
                                            examId,
                                            school: record?.school
                                        });
                                        timer.current = setTimeout(() => {
                                            studentRef?.current?.openModal();
                                        }, 0);


                                    }} style={{ color: '#4ABB6A' }}>{value}</Button>
                                }
                            }
                        }
                        return {
                            title: item?.label,
                            dataIndex: item?.prop,
                            align: "center",
                            width: 140,
                            children: item?.children?.map(element => {
                                return {
                                    title: element?.label,
                                    dataIndex: element?.prop,
                                    align: "center",
                                    width: 70,
                                    sorter: (a, b) => a[element?.prop] - b[element?.prop],
                                }
                            })
                        }
                    })
                })

            }
            setLoading(false);

        } catch (error) {
            setLoading(false);
            console.log(error, 'student-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 handleDownload = async () => {
        try {
            const res = await downloadTableData(responseData);
            if (res?.status === 200) {
                downloadExcelFile(res, `${subtitle}*${subjectName}尖子生情况分析`);
            }

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

        }
    };

    return (
        <div>
            {isShowChart ? (<section className={styles.analysis_content_chart} id={`operationExport${idx}`} >
                <section className={styles.analysis_content_chart_title}>
                    <section className={styles.page_title}>
                        <img src={sectionSrc} className={styles.page_title_img} />
                        <span className={styles.page_title_text}>{subtitle}尖子生情况分析-图表</span>
                        <Space>
                            <Select
                                placeholder="请选择学科"
                                options={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={() => {
                        echartRef?.current?.exportChart();
                    }}>导出图表</Button>)}
                </section>
                <section style={{ display: "flex", alignItems: "center", marginTop:16}}>
                            全市前&nbsp;&nbsp;
                            <Input
                                style={{
                                    padding: "2px 8px",
                                    border: "1px solid #c0c0c0",
                                    borderRadius: 5,
                                    cursor: "pointer",
                                    color: "#c0c0c0",
                                    width: 80,
                                }}
                                min={1}
                                placeholder="请输入"
                                value={topStudentLimit}
                                type="number"
                                onChange={(e) => {
                                    if (!e?.target?.value) {
                                        return;
                                    }
                                    setTopStudentLimit(+e.target.value);
                                }}
                            />&nbsp;
                            名
                            &nbsp;&nbsp;
                            <Button onClick={()=>{
                                setLimit(topStudentLimit);
                            }}>确定</Button>
                        </section>
                <section className={styles.analysis_content_chart_content}>
                    <Spin spinning={loading} tip='计算中，请稍后'>
                        {lengButton?.length > 0 ? (<Echarts2
                            hasTable={false}
                            hasExport={false}
                            ref={echartRef}
                            needTab={true}
                            data={echartData}
                            type={"bar"}
                            lengButton={lengButton}
                            text={`${subtitle}${subjectName}*尖子生情况分析-图表`}

                        />) : <Empty description={"暂无图表数据"} />}
                    </Spin>

                </section>
            </section>) : null}
            {isShowTable ? (<section className={styles.analysis_content_table} id={`operationExport${idx + 1}`}>
                <section className={styles.analysis_content_table_title}>
                    <section className={styles.page_title}>
                        <img src={sectionSrc} className={styles.page_title_img} />
                        <span className={styles.page_title_text}>{subtitle}尖子生情况分析-表格</span>
                        <Space>
                            <Select
                                placeholder="请选择学科"
                                options={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}>
                <section style={{ display: "flex", alignItems: "center" }}>
                            全市前&nbsp;&nbsp;
                            <Input
                                style={{
                                    padding: "2px 8px",
                                    border: "1px solid #c0c0c0",
                                    borderRadius: 5,
                                    cursor: "pointer",
                                    color: "#c0c0c0",
                                    width: 80,
                                }}
                                min={1}
                                placeholder="请输入"
                                value={topStudentLimit}
                                type="number"
                                onChange={(e) => {
                                    if (!e?.target?.value) {
                                        return;
                                    }
                                    setTopStudentLimit(+e.target.value);
                                }}
                            />&nbsp;
                            名
                            &nbsp;&nbsp;
                            <Button onClick={()=>{
                                setLimit(topStudentLimit);
                            }}>确定</Button>
                        </section>
                    <section style={{height:16}}></section>
                    <Table
                        {...tableCommonProps}
                        dataSource={dataSource}
                        columns={columns}
                        locale={{ emptyText: loading ? "计算中，请稍后" : "暂无数据" }}
                        loading={{ spinning: loading, tip: "计算中，请稍后" }}
                    >
                    </Table>
                </section>
            </section>) : null}
            <StudentModal ref={studentRef} params={studentParams} />
        </div>
    )
};


export default TopStudent;