import { useState, useEffect, useRef } from 'react';
import { Row, Col, Button, Select, Tag, Form, Modal, Tooltip, Empty, Spin } from 'antd';
import { QuestionCircleOutlined, LoadingOutlined } from '@ant-design/icons';
import ScreenPage from "@/components/ScreenPage";
import Flex from "@/components/Flex";
import { getExam } from '@/apis/common';
import { getPersonalReport, getTemplateDetail } from '@/apis/report';
import useCurrentExam from '@/stores/useCurrentExam';
import useUserStore from '@/stores/useUserStore';
import useSaveFile from '@/stores/useSaveFile';
import upSrc from "@/assets/image/up.png";
import downSrc from "@/assets/image/down.png";
import editSrc from '@/assets/icon/edit.png';
import downloadSrc from '@/assets/icon/download.png';
import styles from './index.less';
import HomePage from './components/HomePage';
import DataExplain from './components/DataExplain';
import Catalogue from './components/Catalogue';
import OnlineSituation from './components/OnlineSituation';
import SchoolComparison from './components/SchoolComparison';
import SchoolPercentage from './components/SchoolPercentage';
import CurrentExamParams from './components/CurrentExamParams';
import TeacherCrowd from './components/TeacherCrowd';
import TeacherAverage from './components/TeacherAverage';
import TeacherPerformance from './components/TeacherPerformance';
import TopStudent from './components/TopStudent';
import OtherStudent from './components/OtherStudent';
import OptionExaminationSubject from './components/OptionExaminationSubject';
import CombineExaminationSubject from './components/CombineExaminationSubject';
import ChoiceExamAnalysis from './components/ChoiceExamAnalysis';
import OptionalExaminationScoring from './components/OptionalExaminationScoring';
import PaperParams from './components/PaperParams';
import ChoiceQuestionRate from './components/ChoiceQuestionRate';
import LittleQuestion from './components/LittleQuestion';
import KnowledgeAnalysis from './components/KnowledgeAnalysis';
import ContrastExamOnline from './components/ContrastExamOnline';
import ContrastExamRanking from './components/ContrastExamRanking';
import ContrastExamPercentage from './components/ContrastExamPercentage';
import ContrastExamParams from './components/ContrastExamParams';
import KnowledgeComparisonAnalysis from './components/KnowledgeComparisonAnalysis';
import ReportSummary from './components/ReportSummary';
import { savePdf } from '@/utils/file'



const AnalysisPage = (props) => {

    const { idx = '' } = props;
    const { setExamName } = useCurrentExam();
    const { user } = useUserStore();
    const { actionShow, setActionShow } = useSaveFile();

    const [isShow, setIsShow] = useState(false);
    const [params, setParams] = useState({});
    const [subtitle, setSubtitle] = useState('');

    const contentRef = useRef(null);
    const comparisonRef = useRef(null);


    const [isShowExamComparison, setIsShowExamComparison] = useState(false);

    const [isShowExamRanking, setIsShowExamRanking] = useState(false);
    const [examList, setExamList] = useState([]);


    // 选择模板
    const [templateOpen, setTemplateOpen] = useState(false);
    const [selectTemplate, setSelectTemplate] = useState(null);
    const [selectTemplateName, setSelectTemplateName] = useState(null);
    const [templateList, setTemplateList] = useState([]);
    const [form] = Form.useForm();
    const [showPageList, setShowPageList] = useState([]);


    const timer = useRef(null);

    const [isShowExamName, setIsShowExamName] = useState(true);


    const [loading, setLoading] = useState(false);

    useEffect(() => {
        getPersonalReportInit();

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


    useEffect(() => {
        if (!selectTemplate) {
            return;
        }

        selectCurrentTemplate();

    }, [selectTemplate]);


    const examComparisonItems = showPageList?.filter(item => [39, 40, 42, 44].includes(item?.reportItemModel?.id));


    const selectCurrentTemplate = async () => {
        try {
            setLoading(true);
            const res = await getTemplateDetail({ id: selectTemplate });
            if (res.code === 200) {
                setLoading(false);
                let startPage = 0;
                const list = res?.data?.reportItemList?.map(item => {
                    // 设置当前页并递增
                    item.page = startPage;

                    // 特定的 id 集合
                    if ([8, 1, 2, 15, 16, 20, 44, 46].includes(item?.reportItemModel?.id)) {
                        startPage += 1;  // 特定 id 增加 1 页
                    } else {
                        // 其他 id 集合
                        if ([3, 4, 5, 6, 7, 45, 22, 24, 25, 28, 23, 39, 40, 42,48].includes(item?.reportItemModel?.id)) {
                            if (item?.showChart && item?.showTable) {
                                startPage += 2;  // 图表和表格都显示，增加 2 页
                            } else if (item?.showChart) {
                                startPage += 1;  // 图表或表格任意一个显示，增加 1 页
                            } else if (item?.showTable) {
                                startPage += 1;  // 图表或表格任意一个显示，增加 1 页
                            }
                        } else if ([26, 27, 47].includes(item?.reportItemModel?.id)) {
                            if (item?.showTable && item?.showTable) {
                                startPage += 3;  // 图表和表格都显示，增加 3 页
                            } else if (item?.showChart) {
                                startPage += 1;  // 图表或表格任意一个显示，增加 1 页
                            } else if (item?.showTable) {
                                startPage += 1;  // 图表或表格任意一个显示，增加 1 页
                            }
                        }
                    }

                    // 返回修改后的 item，包括更新后的 page 值
                    return {
                        ...item,
                        total: startPage
                    };
                });
                console.log(list, 'list');

                setShowPageList(list);
            }
            setLoading(false);
        } catch (error) {
            setLoading(false);
            console.log(error, 'select-current-template-error');

        }
    }


    const getPersonalReportInit = async () => {
        try {
            const res = await getPersonalReport();
            if (res?.code === 200) {
                setTemplateList(res?.data || []);
                setSelectTemplate(res?.data?.[0]?.id || null);
                setSelectTemplateName(res?.data?.[0]?.title || null);
                return;
            }
        } catch (error) {
            console.log(error, 'personal-report-error');

        }
    };
    const scrollToSection = (ref) => {
        ref.current?.scrollIntoView({ behavior: 'smooth' });
    };

    return (
        <div className={styles.analysis} id={`operationExport${idx}`}>
            <Spin spinning={loading} indicator={<LoadingOutlined />} size="large" tip='加载中，请稍后'>
                <Row gutter={16}>
                    <Col span={24}>
                        <section className={styles.analysis_content} ref={contentRef}>
                            <section style={{ boxSizing: "border-box", padding: 8, backgroundColor: "#fff", display: isShow ? "block" : "none" }} >
                                <ScreenPage
                                    isShow={isShow}
                                    isShowSubject={false}
                                    isShowSchool={false}
                                    onChange={(e) => {

                                        setSubtitle(`${[e?.currentGrade?.[0]?.name, e?.currentSemester?.[0]?.name, e?.currentExamination?.[0]?.name,].filter(item => !!item).join("*")}*`);
                                        setExamName(`${[e?.currentGrade?.[0]?.name, e?.currentSemester?.[0]?.name, e?.currentExamination?.[0]?.name,].filter(item => !!item).join("*")}*`);
                                        setParams({
                                            examId: e?.examId,
                                        });
                                    }}
                                    saveshow={(e) => {
                                        setIsShowExamName(false);
                                        setIsShow(e);
                                    }}
                                />
                            </section>
                            <section className={styles.title}>
                                <section style={{ display: "flex", alignItems: "center" }}>
                                    {subtitle ? (<span style={{ fontSize: 24 }}>
                                        {isShowExamName ? "当前默认最新一次考试：" : '当前考试：'}{subtitle?.slice(0, -1)}
                                    </span>) : null}
                                    <Flex
                                        style={{
                                            padding: "4px 8px",
                                            border: "1px solid #666",
                                            borderRadius: 5,
                                            cursor: "pointer",
                                            width: '200px',
                                            marginLeft: 8
                                        }}
                                        justify='center'
                                        alignItems="center"
                                        onClick={() => {
                                            setIsShow(!isShow);
                                        }}
                                    >
                                        选择考试
                                        <img
                                            src={isShow ? upSrc : downSrc}
                                            width={14}
                                            height={12}
                                            style={{ marginLeft: 5 }}
                                        />
                                    </Flex>
                                    <Tooltip title="如果需要看其他考试与学科，请按”选择考试”">
                                        <QuestionCircleOutlined style={{ fontSize: 18, marginLeft: 8 }} />
                                    </Tooltip>
                                </section>

                                <Flex
                                    style={{
                                        padding: "4px 8px",
                                        border: "1px solid #666",
                                        borderRadius: 5,
                                        cursor: "pointer",
                                        width: '200px',
                                        marginTop: 8
                                    }}
                                    justify='center'
                                    alignItems="center"
                                    onClick={() => {
                                        setTemplateOpen(true);
                                    }}
                                >
                                    {selectTemplateName ? selectTemplateName : '选择报告模板'}
                                    <img
                                        src={editSrc}
                                        width={14}
                                        height={12}
                                        style={{ marginLeft: 5 }}
                                    />
                                </Flex>

                            </section>
                            <div id='test'>

                                {showPageList?.length > 0 ? (showPageList?.map((item) => {

                                    if (item?.reportItemModel?.id === 8) {
                                        return (
                                            <HomePage idx={item?.page} subtitle={subtitle} user={user} />
                                        )
                                    }
                                    if (item?.reportItemModel?.id === 1) {
                                        return (
                                            <DataExplain idx={item?.page} examId={params?.examId} />
                                        )
                                    }
                                    if (item?.reportItemModel?.id === 2) {
                                        return (
                                            <Catalogue idx={item?.page}  modelList={showPageList}/>
                                        )
                                    }

                                    if (item?.reportItemModel?.id === 3) {
                                        return (
                                            <OnlineSituation idx={item?.page} examId={params?.examId} subtitle={subtitle} isShowChart={!!item?.showChart} isShowTable={!!item?.showTable}  actionShow={actionShow}/>
                                        )
                                    }
                                    if (item?.reportItemModel?.id === 4) {
                                        return (
                                            <SchoolComparison idx={item?.page} examId={params?.examId} subtitle={subtitle} isShowChart={!!item?.showChart} isShowTable={!!item?.showTable}  actionShow={actionShow}/>
                                        )
                                    }
                                    if (item?.reportItemModel?.id === 5) {
                                        return (
                                            <SchoolPercentage idx={item?.page} examId={params?.examId} subtitle={subtitle} isShowChart={!!item?.showChart} isShowTable={!!item?.showTable} actionShow={actionShow} />
                                        )
                                    }
                                    if (item?.reportItemModel?.id === 6) {
                                        return (
                                            <CurrentExamParams idx={item?.page} examId={params?.examId} subtitle={subtitle} isShowChart={!!item?.showChart} isShowTable={!!item?.showTable} actionShow={actionShow} />
                                        )
                                    }
                                    if (item?.reportItemModel?.id === 7) {
                                        return (
                                            <TopStudent idx={item?.page} examId={params?.examId} subtitle={subtitle} isShowChart={!!item?.showChart} isShowTable={!!item?.showTable}  actionShow={actionShow}/>
                                        )
                                    }
                                    if (item?.reportItemModel?.id === 15) {
                                        return (
                                            <TeacherCrowd idx={item?.page} examId={params?.examId} subtitle={subtitle}  actionShow={actionShow}/>
                                        )
                                    }
                                    if (item?.reportItemModel?.id === 20) {
                                        return (
                                            <TeacherAverage idx={item?.page} examId={params?.examId} subtitle={subtitle}  actionShow={actionShow}/>
                                        )
                                    }
                                    if (item?.reportItemModel?.id === 16) {
                                        return (
                                            <TeacherPerformance idx={item?.page} examId={params?.examId} subtitle={subtitle} actionShow={actionShow} />
                                        )
                                    }
                                    if (item?.reportItemModel?.id === 45) {
                                        return (
                                            <OtherStudent idx={item?.page} examId={params?.examId} subtitle={subtitle} isShowChart={!!item?.showChart} isShowTable={!!item?.showTable} actionShow={actionShow} />
                                        )
                                    }
                                    if (item?.reportItemModel?.id === 22) {
                                        return (
                                            <OptionExaminationSubject idx={item?.page} subtitle={subtitle} examId={params?.examId} isShowChart={!!item?.showChart} isShowTable={!!item?.showTable}  actionShow={actionShow} />
                                        )
                                    }
                                    if (item?.reportItemModel?.id === 23) {
                                        return (
                                            <CombineExaminationSubject idx={item?.page} examId={params?.examId} subtitle={subtitle} isShowChart={!!item?.showChart} isShowTable={!!item?.showTable} actionShow={actionShow} />
                                        )
                                    }
                                    if (item?.reportItemModel?.id === 24) {
                                        return (
                                            <ChoiceExamAnalysis idx={item?.page} examId={params?.examId} subtitle={subtitle} isShowChart={!!item?.showChart} isShowTable={!!item?.showTable}  actionShow={actionShow}/>
                                        )
                                    }
                                    if (item?.reportItemModel?.id === 25) {
                                        return (
                                            <OptionalExaminationScoring idx={item?.page} examId={params?.examId} subtitle={subtitle} isShowChart={!!item?.showChart} isShowTable={!!item?.showTable}  actionShow={actionShow}/>
                                        )
                                    }
                                    if (item?.reportItemModel?.id === 28) {
                                        return (
                                            <PaperParams idx={item?.page} examId={params?.examId} subtitle={subtitle} isShowChart={!!item?.showChart} isShowTable={!!item?.showTable}  actionShow={actionShow}/>
                                        )
                                    }
                                    if (item?.reportItemModel?.id === 27) {
                                        return (
                                            <ChoiceQuestionRate idx={item?.page} examId={params?.examId} subtitle={subtitle} isShowChart={!!item?.showChart} isShowTable={!!item?.showTable} actionShow={actionShow} />
                                        )
                                    }
                                    if (item?.reportItemModel?.id === 26) {
                                        return (
                                            <LittleQuestion idx={item?.page} examId={params?.examId} subtitle={subtitle} isShowChart={!!item?.showChart} isShowTable={!!item?.showTable}  actionShow={actionShow}/>
                                        )
                                    }
                                    if (item?.reportItemModel?.id === 47) {
                                        return (
                                            <KnowledgeAnalysis idx={item?.page} examId={params?.examId} subtitle={subtitle} isShowChart={!!item?.showChart} isShowTable={!!item?.showTable} actionShow={actionShow} />
                                        )
                                    }
                                })) : <Empty description='暂无整体报告' />}
                                {examComparisonItems?.length > 0 && !isShowExamComparison && (
                                    <section className={styles.analysis_tip}>
                                        <section>
                                            {subtitle}分析报告中“当前考试分析”部分已结束，您可以点击{" "}
                                            <Button
                                                type="link"
                                                style={{ color: "#4ABB6A", textDecoration: "underline", fontSize: 18 }}
                                                onClick={() => {
                                                    setIsShowExamComparison(true);
                                                    timer.current = setTimeout(() => scrollToSection(comparisonRef), 0);
                                                }}
                                            >
                                                考试对比
                                            </Button>{" "}
                                            查看当前考试与历届历次考试的对比分析
                                        </section>
                                    </section>
                                )}
                                {
                                    (examComparisonItems?.length > 0) ? (<div ref={comparisonRef} style={{ display: isShowExamComparison ? 'block' : "none" }}>
                                        <section className={styles.exam_ranking}>
                                            <Flex>
                                                <Flex
                                                    style={{
                                                        display: "flex",
                                                        alignItems: "center",
                                                        color: "#8a8a8a",
                                                    }}
                                                >
                                                    {" "}
                                                    当前考试 : &nbsp;
                                                    <h3
                                                        style={{
                                                            color: "black",
                                                        }}
                                                    >
                                                        {subtitle?.slice(0, -1)}
                                                    </h3>
                                                </Flex>
                                            </Flex>
                                            <section className={styles.ranking}>
                                                <div className={styles.ranking_title}>对比考试: &nbsp;</div>
                                                <section className={styles.ranking_content}>
                                                    {examList?.filter(item => item?.id !== params?.examId)?.map((item) => {
                                                        return (
                                                            <Tag
                                                                key={item.id}
                                                                style={{
                                                                    color: "black",
                                                                    fontWeight: "bold",
                                                                    fontSize: 14,
                                                                    marginTop: 4
                                                                }}
                                                            >
                                                                {`${item?.term}*${item?.semester}*${item?.examName}`}
                                                            </Tag>
                                                        );
                                                    })}
                                                    <div
                                                        className={styles.ranking_select}
                                                        onClick={() => {
                                                            setIsShowExamRanking(!isShowExamRanking);
                                                        }}
                                                    >
                                                        选择考试
                                                        <img
                                                            src={isShowExamRanking ? upSrc : downSrc}
                                                            width={14}
                                                            height={12}
                                                            style={{ marginLeft: 5 }}
                                                        />
                                                    </div>
                                                </section>
                                            </section>
                                            <ScreenPage
                                                isShow={isShowExamRanking}
                                                isSingle={false}
                                                isShowSubject={false}
                                                isShowSchool={false}
                                                onChange={(e) => {

                                                    if (!isShowExamRanking) {
                                                        return;
                                                    }

                                                    setParams({
                                                        ...params,
                                                        schools: e?.currentSchool?.[0]?.schoolList?.map(item => item?.id) || e?.currentSchool?.map(item => item?.id),
                                                    });
                                                    const term = e?.currentGrade?.map(item => item?.name);
                                                    const semester = e?.currentSemester?.map(item => item?.name);
                                                    const examName = e?.currentExamination?.map(item => item?.name);
                                                    getExam({
                                                        term,
                                                        semester,
                                                        examName,
                                                    }).then(res => {
                                                        if (res.code === 200) {
                                                            setExamList(res.data || []);
                                                        }

                                                    }).catch(error => {
                                                        console.log(error, 'get-exam-error');

                                                    })
                                                }}
                                                saveshow={(e) => {
                                                    setIsShowExamRanking(e);
                                                }}
                                            />
                                        </section>
                                        {
                                            showPageList?.map(item => {

                                                if (item?.reportItemModel?.id === 39) {
                                                    return (
                                                        <ContrastExamRanking idx={item?.page} subtitle={subtitle} examId={params?.examId} examList={examList} isShowChart={!!item?.showChart} isShowTable={!!item?.showTable}  actionShow={actionShow}/>
                                                    )
                                                }
                                                if (item?.reportItemModel?.id === 48) {
                                                    return (
                                                        <ContrastExamOnline idx={item?.page} subtitle={subtitle} examId={params?.examId} examList={examList} isShowChart={!!item?.showChart} isShowTable={!!item?.showTable}   actionShow={actionShow}/>
                                                    )
                                                }
                                                if (item?.reportItemModel?.id === 40) {
                                                    return (
                                                        <ContrastExamPercentage idx={item?.page} subtitle={subtitle} examId={params?.examId} examList={examList} isShowChart={!!item?.showChart} isShowTable={!!item?.showTable}  actionShow={actionShow}/>
                                                    )
                                                }
                                                if (item?.reportItemModel?.id === 42) {
                                                    return (
                                                        <ContrastExamParams idx={item?.page} subtitle={subtitle} examId={params?.examId} examList={examList} isShowChart={!!item?.showChart} isShowTable={!!item?.showTable}  actionShow={actionShow}/>
                                                    )
                                                }
                                                if (item?.reportItemModel?.id === 44) {
                                                    return (
                                                        <KnowledgeComparisonAnalysis idx={item?.page} subtitle={subtitle} examId={params?.examId} examList={examList} actionShow={actionShow} />
                                                    )
                                                }
                                            })
                                        }
                                    </div>) : null}
                            </div>
                            {showPageList?.length > 0 ? (showPageList?.map((item) => {
                                if (item?.reportItemModel?.id === 46) {
                                    return (
                                        <ReportSummary idx={item?.page} item={item} />
                                    )
                                }
                            })) : null}
                            {showPageList?.length > 0 ? (<section className={styles.download}>
                                <Flex
                                    onClick={() => {
                                        setActionShow(false);
                                        savePdf(showPageList?.[showPageList?.length - 1]?.total, selectTemplateName)
                                    }}
                                    style={{
                                        padding: "4px 8px",
                                        border: "1px solid #666",
                                        borderRadius: 5,
                                        cursor: "pointer",
                                        width: '200px',
                                        marginTop: 8
                                    }}
                                    justify='center'
                                    alignItems="center"
                                >
                                    下载报告
                                    <img
                                        src={downloadSrc}
                                        width={14}
                                        height={12}
                                        style={{ marginLeft: 5 }}
                                    />
                                </Flex>
                            </section>) : null}

                            <section style={{ height: 32 }}></section>
                        </section>
                    </Col>
                </Row>
            </Spin>
            <Modal
                title='报告模板选择'
                centered
                open={templateOpen}
                destroyOnClose
                width={600}
                maskClosable={false}
                onCancel={() => {
                    setTemplateOpen(false);
                    setSelectTemplate('');
                }}
                onOk={() => {
                    setTemplateOpen(false);
                }}
            >
                <Form
                    form={form}
                >
                    <Form.Item label="报告模板">
                        <Select placeholder="请选择报告模板" value={selectTemplateName} onChange={(value, option) => {
                            if (!value) {
                                setSelectTemplate(null);
                                setSelectTemplateName(null);
                                return;
                            }
                            setSelectTemplate(value);
                            setSelectTemplateName(option?.label);
                        }} options={templateList?.map(item => {
                            return {
                                value: item.id,
                                label: item.title
                            }
                        })} style={{ width: '100%' }} />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
};


export default AnalysisPage;