
import { useState, useEffect, useRef } from 'react';
import { Space, Select, Button, Spin, Empty, Table, Input, Flex, Tooltip } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { getCriticalStudentAnalysis, getBadSubjectStudentAnalysis, getRashStudentAnalysis } 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 OtherStudent = (props) => {



    const { examId = '', subtitle = '', isShowChart = false, isShowTable = false,idx='' ,actionShow = true } = props;

    const selectButton = ["临界生", "优生劣科"];
    const [activeButtons, setActiveButtons] = useState(selectButton[0]);
    const [selected, setSelected] = useState('critical');

    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 [limit, setLimit] = useState(50);
    const [rateOn, setRateOn] = useState(5);
    const [rateUnder, setRateUnder] = useState(5);

    const [up, setUp] = useState(610);
    const [down, setDown] = useState(600);
    const [criticalScore, setCriticalScore] = useState();
    const timer = useRef(null);


    const [tmpLimit, setTmpLimit] = useState(50);
    const [tmpRateOn, setTmpRateOn] = useState(5);
    const [tmpRateUnder, setTmpRateUnder] = useState(5);

    const [tmpUp, setTmpUp] = useState(610);
    const [tmpDown, setTmpDown] = useState(600);

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

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

    }, [examId, schoolIds, subjectId, selected, limit, rateOn, rateUnder, up, down]);


    const init = async () => {
        const API = {
            critical: getCriticalStudentAnalysis,
            badSubject: getBadSubjectStudentAnalysis,
            rash: getRashStudentAnalysis,
        };

        try {
            setLoading(true);
            const res = await API?.[selected]({
                examId,
                limit: limit,
                rateOn: selected === 'critical' ? rateOn : up,
                rateUnder: selected === 'critical' ? rateUnder : down,
                subjectId: subjectId,
                schools: schoolIds
                // ...otherParams
            });
            if (res?.code === 200) {
                if (selected === 'critical') {
                    setCriticalScore(res?.name);
                }
                setResponseData(res);
                setLoading(false);
                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: 100,
                                    sorter: element?.label !== "标签" ? (a, b) => a[element?.prop] - b[element?.prop] : false,
                                }
                            })
                        }
                    })
                })

            }
            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}*${activeButtons === '临界生' ? subjectName : ''}${activeButtons}情况分析`);
            }

        } 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}{activeButtons}情况分析-图表</span>
                        <Space>
                            {selected !== 'badSubject' ? (
                                <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);
                                    }}
                                />
                            ) : null}
                            <SchoolChoice onChange={(value) => {
                                setSchoolIds(value);
                            }} />
                        </Space>

                    </section>
                    {actionShow && (<Button type='primary' style={{ fontSize: 16 }} onClick={() => {
                        echartRef?.current?.exportChart();
                    }}>导出图表</Button>)}
                </section>
                <Flex alignItems="center" style={{ marginRight: 12 }}>
                    {selected === "critical" && (
                        <>
                            全市前&nbsp;&nbsp;
                            <Input
                                style={{
                                    padding: "2px 8px",
                                    border: "1px solid #c0c0c0",
                                    borderRadius: 5,
                                    cursor: "pointer",
                                    color: "#c0c0c0",
                                    width: 80,
                                }}
                                min={1}
                                placeholder="请输入"
                                value={tmpLimit}
                                type="number"
                                onChange={(e) => {
                                    setTmpLimit(+e.target.value);
                                }}
                            />&nbsp;
                            名
                            &nbsp;{criticalScore ? `分数为${criticalScore}分` : ''}，上限浮动&nbsp;&nbsp;
                            <Input
                                style={{
                                    padding: "2px 8px",
                                    border: "1px solid #c0c0c0",
                                    borderRadius: 5,
                                    cursor: "pointer",
                                    color: "#c0c0c0",
                                    width: 80,
                                }}
                                min={1}
                                placeholder="请输入"
                                value={tmpRateOn}
                                type="number"
                                onChange={(e) => {
                                    setTmpRateOn(+e.target.value);
                                }}
                            />
                            &nbsp;&nbsp;分， 下限浮动&nbsp;&nbsp;
                            <Input
                                style={{
                                    padding: "2px 8px",
                                    border: "1px solid #c0c0c0",
                                    borderRadius: 5,
                                    cursor: "pointer",
                                    color: "#c0c0c0",
                                    width: 80,
                                }}
                                min={1}
                                placeholder="请输入"
                                value={tmpRateUnder}
                                type="number"
                                onChange={(e) => {
                                    setTmpRateUnder(+e.target.value);
                                }}
                            />
                            &nbsp;&nbsp;分
                            &nbsp;
                            <Button onClick={() => {
                                setLimit(tmpLimit);
                                setRateOn(tmpRateOn);
                                setRateUnder(tmpRateUnder);
                            }}>确定</Button>
                        </>
                    )}

                    {selected === 'badSubject' && (
                        <>
                            总分分数段区间设置为上限&nbsp;&nbsp;
                            <Input
                                style={{
                                    padding: "2px 8px",
                                    border: "1px solid #c0c0c0",
                                    borderRadius: 5,
                                    cursor: "pointer",
                                    color: "#c0c0c0",
                                    width: 80,
                                }}
                                min={1}
                                max={1000}
                                placeholder="请输入"
                                value={tmpUp}
                                type="number"
                                onChange={(e) => {
                                    setTmpUp(+e.target.value);
                                }}
                            />
                            &nbsp;&nbsp;分，
                            下限&nbsp;
                            <Input
                                style={{
                                    padding: "2px 8px",
                                    border: "1px solid #c0c0c0",
                                    borderRadius: 5,
                                    cursor: "pointer",
                                    color: "#c0c0c0",
                                    width: 80,
                                }}
                                min={1}
                                max={1000}
                                placeholder="请输入"
                                value={tmpDown}
                                type="number"
                                onChange={(e) => {
                                    setTmpDown(+e.target.value);
                                }}
                            />
                            &nbsp;&nbsp;分。
                            &nbsp;
                            <Button
                                onClick={() => {
                                    setUp(tmpUp);
                                    setDown(tmpDown);
                                }}
                            >
                                确定
                            </Button>
                            &nbsp;
                            &nbsp;
                            <Tooltip title="在该区间的学生群体中，个别学生的学科分数低于区间内学生群体平均分的标记为劣科。">
                                <QuestionCircleOutlined />
                            </Tooltip>

                        </>
                    )}

                </Flex>
                <section style={{ marginTop: 8 }}>
                    {selectButton.map((but, index) => {
                        return (
                            <Button
                                size={"small"}
                                key={index}
                                style={{
                                    marginRight: 10,
                                    backgroundColor: activeButtons == but ? "#e9f7ee" : "",
                                    color: activeButtons == but ? "#3eb463" : "",
                                    borderColor: activeButtons == but ? "#e9f7ee" : "",
                                }}
                                onClick={() => {
                                    setActiveButtons(but);
                                    if (but === '临界生') {
                                        setSelected('critical');
                                        return;
                                    }
                                    if (but === '优生劣科') {
                                        setSelected('badSubject');
                                        return;
                                    }
                                    if (but === '冒进生') {
                                        setSelected('rash');
                                        return;
                                    }
                                }}
                            >
                                {but}
                            </Button>
                        );
                    })}
                </section>
                <section className={styles.analysis_content_chart_content} style={{ marginTop: -4 }}>
                    <Spin spinning={loading} tip='计算中，请稍后'>
                        {lengButton?.length > 0 ? (<Echarts2
                            hasTable={false}
                            ref={echartRef}
                            hasExport={false}
                            needTab={true}
                            data={echartData}
                            type={"bar"}
                            lengButton={lengButton}
                            text={`${subtitle}${subjectName}*${activeButtons}情况分析-图表`}

                        />) : <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}{activeButtons}情况分析-表格</span>
                            <Space>
                                {selected !== 'badSubject' ? (
                                    <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);
                                        }}
                                    />
                                ) : null}
                                <SchoolChoice onChange={(value) => {
                                    setSchoolIds(value);
                                }} />
                            </Space>

                        </section>
                        {actionShow && (<Button type='primary' style={{ fontSize: 16 }} onClick={handleDownload}>导出表格</Button>)}
                    </section>
                    <Flex alignItems="center" style={{ marginRight: 12 }}>
                        {selected === "critical" && (
                            <>
                                全市前&nbsp;&nbsp;
                                <Input
                                    style={{
                                        padding: "2px 8px",
                                        border: "1px solid #c0c0c0",
                                        borderRadius: 5,
                                        cursor: "pointer",
                                        color: "#c0c0c0",
                                        width: 80,
                                    }}
                                    min={1}
                                    max={5}
                                    placeholder="请输入"
                                    value={limit}
                                    type="number"
                                    onChange={(e) => {
                                        setLimit(+ e.target.value);
                                    }}
                                />&nbsp;
                                名
                                &nbsp;{criticalScore ? `分数为${criticalScore}分` : ''}，上限浮动&nbsp;&nbsp;
                                <Input
                                    style={{
                                        padding: "2px 8px",
                                        border: "1px solid #c0c0c0",
                                        borderRadius: 5,
                                        cursor: "pointer",
                                        color: "#c0c0c0",
                                        width: 80,
                                    }}
                                    min={1}
                                    max={5}
                                    placeholder="请输入"
                                    value={rateOn}
                                    type="number"
                                    onChange={(e) => {
                                        setRateOn(+e.target.value);
                                    }}
                                />
                                &nbsp;&nbsp;分, 下限浮动&nbsp;&nbsp;
                                <Input
                                    style={{
                                        padding: "2px 8px",
                                        border: "1px solid #c0c0c0",
                                        borderRadius: 5,
                                        cursor: "pointer",
                                        color: "#c0c0c0",
                                        width: 80,
                                    }}
                                    min={1}
                                    placeholder="请输入"
                                    value={rateUnder}
                                    type="number"
                                    onChange={(e) => {
                                        setRateUnder(+e.target.value);
                                    }}
                                />
                                &nbsp;&nbsp;分
                            </>
                        )}

                        {selected === 'badSubject' && (
                            <>
                                总分分数段区间设置为上限&nbsp;&nbsp;
                                <Input
                                    style={{
                                        padding: "2px 8px",
                                        border: "1px solid #c0c0c0",
                                        borderRadius: 5,
                                        cursor: "pointer",
                                        color: "#c0c0c0",
                                        width: 80,
                                    }}
                                    min={1}
                                    max={1000}
                                    placeholder="请输入"
                                    value={up}
                                    type="number"
                                    onChange={(e) => {
                                        setUp(+e.target.value);
                                    }}
                                />
                                &nbsp;&nbsp;分，
                                下限&nbsp;
                                <Input
                                    style={{
                                        padding: "2px 8px",
                                        border: "1px solid #c0c0c0",
                                        borderRadius: 5,
                                        cursor: "pointer",
                                        color: "#c0c0c0",
                                        width: 80,
                                    }}
                                    min={1}
                                    max={1000}
                                    placeholder="请输入"
                                    value={down}
                                    type="number"
                                    onChange={(e) => {
                                        setDown(+e.target.value);
                                    }}
                                />
                                &nbsp;&nbsp;分。<Tooltip title="在该区间的学生群体中，个别学生的学科分数低于区间内学生群体平均分的标记为劣科。">
                                    <QuestionCircleOutlined />
                                </Tooltip>

                            </>
                        )}
                    </Flex>
                    <section className={styles.analysis_content_table_content}>
                        <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 OtherStudent;