

import { useState, useEffect, useRef } from 'react';
import { Space, Select, Button, Spin, Table } from 'antd';
import { getAnswerRate } from '@/apis/leader';
import { getSubjectList } 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-6.png';
import styles from './index.less';

const ChoiceQuestionRate = (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 [expandedRowKeys, setExpandedRowKeys] = useState([]);
    const [echartData1, setEchartData1] = useState({});
    const [echartData2, setEchartData2] = useState({});
    const [lengButton, setLengButton] = useState([]);
    const echartRef1 = useRef();
    const echartRef2 = useRef();

    const [singleSubjectList, setSingleSubjectList] = useState([]);

    const expandableConfig = {
        expandedRowKeys: expandedRowKeys,
        expandIconColumnIndex: 2,
        onExpand: (expanded, record) => {
            if (expanded) {
                setExpandedRowKeys([...expandedRowKeys, record.id]);
            } else {
                setExpandedRowKeys(expandedRowKeys?.filter((k) => k !== record.id));
            }
        },
    };


    useEffect(() => {
        singleSubjectInit();
    }, []);
    useEffect(() => {

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

    }, [examId, schoolIds, subjectId]);


    const init = async () => {
        setLoading(true);
        try {
            const res = await getAnswerRate({
                examId,
                subjectId: subjectId,
                schools: schoolIds
            });
            if (res?.code === 200) {
                setLoading(false);
                setResponseData(res);
                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?.rate?.[0]?.data?.length || !res?.columnDiagramResult?.rate?.[0]?.xdata?.length) {
                    return;
                }
                setLengButton([res?.columnDiagramResult?.rate?.[0]?.lineName]);
                setEchartData1(() => {
                    return {
                        xAxis: {
                            name: "",
                            type: "category",
                            axisTick: { show: false },
                            data: res?.columnDiagramResult?.rate?.[0]?.xdata,
                        },
                        yAxis: {
                            name: '',
                        },
                        tooltip: {
                            show: true,
                        },
                        yChartData: [
                            {
                                name: res?.columnDiagramResult?.rate?.[0]?.lineName,
                                data: res?.columnDiagramResult?.rate?.[0]?.data
                            }
                        ],
                    }
                });

                setEchartData2(() => {
                    return {
                        radarText: {
                            indicator: res?.columnDiagramResult?.rate?.[0]?.xdata?.map(item => {
                                return {
                                    name: item,
                                    max: 100
                                }
                            }),
                            yChartData: [
                                {
                                    name: res?.columnDiagramResult?.rate?.[0]?.lineName,
                                    data: res?.columnDiagramResult?.rate?.[0]?.data,
                                },
                            ],
                        },
                    }
                })

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

        }
    };


    const singleSubjectInit = async () => {
        try {
            const res = await getSubjectList();
            if (res?.code === 200) {
                const element = res?.data?.find(item => item?.cname === '数学');
                setSubjectId(element?.id || '');
                setSubjectName(element?.cname || null);
                setSingleSubjectList(() => {
                    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={singleSubjectList}
                                        value={subjectName}
                                        style={{ marginLeft: 20, width: "120px" }}
                                        onChange={(value, options) => {
                                            if (!value) {
                                                return;
                                            }
                                            setSubjectName(options?.label);
                                            setSubjectId(value);
                                        }}
                                    />
                                    <SchoolChoice onChange={(value) => {
                                        setSchoolIds(value);
                                    }} />
                                </Space>


                            </section>
                            {actionShow && ( <Button type='primary' style={{ fontSize: 16 }} onClick={() => {
                                echartRef1?.current?.exportChart();
                            }}>导出图表</Button>)}
                        </section>
                        <section className={styles.analysis_content_chart_content}>
                            <Spin spinning={loading} tip='计算中，请稍后'>
                                <Echarts
                                    text={`考试选择题答题率*${subtitle}${subjectName}*折线图`}
                                    data={echartData1}
                                    ref={echartRef1}
                                    isShow={false}
                                    type={"line"}
                                    needTab={true}
                                    lengButton={lengButton}
                                    hasExport={false}
                                    hasTable={false}
                                />
                            </Spin>
                        </section>
                    </section>
                    <section className={styles.analysis_content_chart} id={`operationExport${idx + 1}`}>
                        <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={singleSubjectList}
                                        value={subjectName}
                                        style={{ marginLeft: 20, width: "120px" }}
                                        onChange={(value, options) => {
                                            if (!value) {
                                                return;
                                            }
                                            setSubjectName(options?.label);
                                            setSubjectId(value);
                                        }}
                                    />
                                    <SchoolChoice onChange={(value) => {
                                        setSchoolIds(value);
                                    }} />
                                </Space>


                            </section>
                            {actionShow && (<Button type='primary' style={{ fontSize: 16 }} onClick={() => {
                                echartRef2?.current?.exportChart();
                            }}>导出图表</Button>)}
                        </section>
                        <section className={styles.analysis_content_chart_content}>
                            <Spin spinning={loading} tip='计算中，请稍后'>
                                <Echarts
                                    text={`考试选择题答题率*${subtitle}${subjectName}*雷达图`}
                                    data={echartData2}
                                    ref={echartRef2}
                                    isShow={false}
                                    type={"radar"}
                                    needTab={true}
                                    lengButton={lengButton}
                                    hasExport={false}
                                    hasTable={false}
                                />
                            </Spin>
                        </section>
                    </section>
                </>
            ) : null}
            {isShowTable ? (<section className={styles.analysis_content_table} id={`operationExport${idx + 2}`}>
                <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}>
                    <Table
                        {...tableCommonProps}
                        dataSource={dataSource}
                        columns={columns}
                        locale={{ emptyText: loading ? "计算中，请稍后" : "暂无数据" }}
                        loading={{ spinning: loading, tip: "计算中，请稍后" }}
                        expandable={expandableConfig}
                    >
                    </Table>
                </section>
            </section>) : null}
        </div>
    )
};

export default ChoiceQuestionRate;