import { useEffect,useState } from "react";
import { Button,Select,Table,Spin } from "antd";
import Echarts from "@/components/Echarts";
import { getQuestionParams} from '@/apis/leader';
import { getSubjectList } from '@/apis/common';
import ScreenPage from "@/components/ScreenPage";
import Flex from "@/components/Flex";
import upSrc from "@/assets/image/up.png";
import downSrc from "@/assets/image/down.png";
import { downloadTableData } from '@/apis/download';
import { downloadExcelFile } from '@/utils/file';

const QualityPage = () => {

    const [isShow, setIsShow] = useState(false);
    const [tableIsShow, setTableIsShow] = useState(false);




    const [subtitle, setSubtitle] = useState('');
    const [dataSource, setDataSource] = useState([]);
    const [params, setParams] = useState({});
    const [columns, setColumns] = useState([]);
    const [loading, setLoading] = useState(false);
    const [echartData, setEchartData] = useState({});
    const [lengButton, setLengButton] = useState([]);
    const [expandedKeys, setExpandedKeys] = useState([]);

    const [subjectId, setSubjectId] = useState('');
    const [subjectName, setSubjectName] = useState(null);

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

    const [responseData1, setResponseData1] = useState({});
    useEffect(() => {
        if (!Object.values(params).length > 0 || !subjectId) {
            return;
        }
        paramsInit();

    }, [params?.examId, subjectId, params?.schools]);


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


    const singleSubjectInit = async () => {
        try {
            const res = await getSubjectList();
            if (res?.code === 200) {
                setSubjectId(res?.data?.[0]?.id || '');
                setSubjectName(res?.data?.[0]?.cname || '');
                setSingleSubjectList(() => {
                    return res?.data?.map(item => {
                        return {
                            label: item?.cname,
                            value: item?.id
                        }
                    })
                })
            }

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

        }
    };


    const paramsInit = async () => {
        setLoading(true);
        try {
            const res = await getQuestionParams({
                ...params,
                subjectId,
            });
            if (res?.code === 200) {
                setLoading(false);
                setResponseData1(res);
                setExpandedKeys([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) {
                    return;
                }

                function handData(obj = {}) {

                    let arr = [];
                    Object.keys(obj).forEach((key) => {
                        arr = arr.concat(obj[key]);
                    });
                    return arr.map(it => {
                        return {
                            name: it?.lineName,
                            data: it?.data
                        }
                    })
                }

                setLengButton(handData(res?.columnDiagramResult)?.map(item => item?.name));


                setEchartData(() => {

                    return {
                        xAxis: {
                            name: "",
                            type: "category",
                            axisTick: { show: false },
                            data: res?.columnDiagramResult?.bzfz?.[0]?.xdata,
                        },
                        yAxis: {
                            name: '',
                        },
                        tooltip: {
                            show: true,
                        },
                        yChartData: handData(res?.columnDiagramResult),
                    }
                })


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

        }
    };


    ////////////////////////////
    //展开表格行
    const expandableConfig = {
        expandedRowKeys: expandedKeys,
        defaultExpandedRowKeys: [dataSource?.[0]?.id,dataSource?.[0]?.children?.[0]?.id],
        onExpand: (expanded, record) => {
            if (expanded) {
                setExpandedKeys([...expandedKeys, record.id]);
            } else {
                setExpandedKeys(expandedKeys.filter((k) => k !== record.id));
            }
        },
    };

    const tableCommonProps = {
        style: { maxHHeight: 460, },
        rowKey: "id",
        scroll: { x: 1400, y: 340 },
        sticky: true,
        pagination: false,
    };

    const handleDownload1 = async () => {
        try {
            const res = await downloadTableData(responseData1);
            if (res?.status === 200) {
                downloadExcelFile(res, `${subtitle}*${subjectName}*考试试卷参数分析`);
            }

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

        }
    };

    ///////////////////////////////
    return (
        <div style={{ padding: 20 }}>
            {
                <ScreenPage
                    isTeacher={true}
                    isShow={isShow}
                    isShowSubject={false}
                    onChange={(e) => {
                        setSubtitle([e?.currentGrade?.[0]?.name, e?.currentSemester?.[0]?.name, e?.currentExamination?.[0]?.name].filter(item => !!item).join("*"));
                        setParams({
                            examId: e?.examId,
                            schools: e?.currentSchool?.[0]?.schoolList?.map(item => item?.id) || e?.currentSchool?.map(item => item?.id),
                        })
                    }}
                    saveshow={(e) => {
                        setIsShow(e);
                    }}
                />
            }
            {/* 标题 */}
            <Flex
                style={{
                    display: "flex",
                    alignItems: "center",
                    margin: "20px 0",
                    gap: 12,
                }}
                justify="space-betweens"
                alignItems="center"
            >
                <Flex style={{ flex: 1 }} alignItems="center">
                    <Flex
                        style={{
                            display: "flex",
                            alignItems: "center",
                            color: "#8a8a8a",
                        }}
                    >
                        当前考试试卷参数分析 : &nbsp;
                        <h3
                            style={{
                                color: "black",
                            }}
                        >
                            {subtitle}
                        </h3>
                    </Flex>
                    <Select
                        placeholder="请选择学科"
                        options={singleSubjectList}
                        value={subjectName}
                        style={{ marginLeft: 20, width: "120px" }}
                        onChange={(value, option) => {
                            if (!value) {
                                return;
                            }
                            setSubjectName(option?.label);
                            setSubjectId(value);
                        }}
                    />
                </Flex>
                <Flex
                    style={{
                        padding: "4px 8px",
                        border: "1px solid #666",
                        borderRadius: 5,
                        cursor: "pointer",
                    }}
                    alignItems="center"
                    onClick={() => {
                        setIsShow(!isShow);
                    }}
                >
                    选择考试和学校
                    <img
                        src={isShow ? upSrc : downSrc}
                        width={14}
                        height={12}
                        style={{ marginLeft: 5 }}
                    />
                </Flex>
            </Flex>
            {/* 表格 */}
            {!tableIsShow ? (
                <Table
                    {...tableCommonProps}
                    dataSource={dataSource}
                    columns={columns}
                    loading={loading}
                    rowKey="id"
                    expandable={expandableConfig}

                >
                </Table>
            ) : (
                <Spin spinning={loading} tip='图表加载中'>
                    <Echarts
                        data={echartData}
                        // type={"radar"}
                        // type={"line"}
                        // type={"pie"}
                        type={"bar"}
                        text={`考试试卷参数分析*${subtitle}*${subjectName}`}
                        lengButton={lengButton}
                        onTableClick={(e) => {
                            setTableIsShow(false);
                        }}
                    // lengButton={["个人得分率", "学校得分率", "区县得分率", "全市得分率"]}
                    />
                </Spin>

            )}
            {!tableIsShow && (
                <Flex style={{ marginTop: 8 }}>
                    <Button
                        type="primary"
                        style={{ marginRight: 10, margintop: 10 }}
                        onClick={handleDownload1}
                    >
                        导出表格
                    </Button>
                    <Button
                        type="primary"
                        onClick={() => {
                            //关闭图表
                            setTableIsShow(true);
                        }}
                    >
                        显示为图表
                    </Button>
                </Flex>
            )}
        
        </div>
    );
};

export default QualityPage;
