import { useState, useEffect, useRef } from 'react';
import { Row, Col, Button, Select, Tag, Form, Modal, Tooltip } from 'antd';
import { QuestionCircleOutlined } 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 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 TopStudent from './components/TopStudent';
import OtherStudent from './components/OtherStudent';
import OptionExaminationSubject from './components/OptionExaminationSubject';
import CombineExaminationSubject from './components/CombineExaminationSubject';
import LittleQuestion from './components/LittleQuestion';
import KnowledgeAnalysis from './components/KnowledgeAnalysis';
import ContrastExamRanking from './components/ContrastExamRanking';
import ContrastExamPercentage from './components/ContrastExamPercentage';
import ContrastExamParams from './components/ContrastExamParams';
import KnowledgeComparisonAnalysis from './components/KnowledgeComparisonAnalysis';



const AnalysisPage = () => {


    const { setExamName } = useCurrentExam();
    const { user } = useUserStore();

    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);

    useEffect(() => {
        getPersonalReportInit();

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


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

        selectCurrentTemplate();

    }, [selectTemplate]);



    const selectCurrentTemplate = async () => {
        try {
            const res = await getTemplateDetail({ id: selectTemplate });
            if (res.code === 200) {
                setShowPageList(res?.data?.reportItemList || []);

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

        }
    }


    const getPersonalReportInit = async () => {
        try {
            const res = await getPersonalReport();
            if (res?.code === 200) {
                const roleType = localStorage.getItem('userRoleType');
                console.log(typeof +roleType, '用户');


                console.log(res?.data, '123');
                const list = res?.data?.filter(item => item?.reportType === +roleType);
                console.log(list, '模板列表');

                setTemplateList(() => {
                    return res?.data?.filter(item => item?.reportType === +roleType);

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

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

    return (
        <div className={styles.analysis}>


            <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);
                                }}
                            >
                                选择报告模板
                                <img
                                    src={editSrc}
                                    width={14}
                                    height={12}
                                    style={{ marginLeft: 5 }}
                                />
                            </Flex>

                        </section>
                        <HomePage subtitle={subtitle} user={user} />
                        <DataExplain examId={params?.examId} />
                        <Catalogue />
                        <OnlineSituation examId={params?.examId} subtitle={subtitle} />
                        <SchoolComparison examId={params?.examId} subtitle={subtitle} />
                        <SchoolPercentage examId={params?.examId} subtitle={subtitle} />
                        <CurrentExamParams examId={params?.examId} subtitle={subtitle} />
                        <TeacherCrowd examId={params?.examId} subtitle={subtitle} />
                        <TopStudent examId={params?.examId} subtitle={subtitle} />
                        <OtherStudent examId={params?.examId} subtitle={subtitle} />

                        {/* 选考科目分布分析 */}
                        <OptionExaminationSubject subtitle={subtitle} examId={params?.examId} />
                        {/* 选考科目分布分析 */}

                        {/* 选考组合分布分析 */}
                        <CombineExaminationSubject examId={params?.examId} subtitle={subtitle} />
                        {/* 选考组合分布分析 */}

                        {/* 考试各小题分析 */}
                        <LittleQuestion examId={params?.examId} subtitle={subtitle} />

                        {/* 学科知识点分析 */}
                        <KnowledgeAnalysis examId={params?.examId} subtitle={subtitle} />
                        {!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>
                        ) : null}

                        {isShowExamComparison ? (<section className={styles.exam} ref={comparisonRef}>

                            <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>
                            {/*对比考试排名情况分析 */}
                            <ContrastExamRanking subtitle={subtitle} examId={params?.examId} examList={examList} />
                            {/*对比考试排名情况分析 */}
                            {/* 对比考试百分比情况分析 */}
                            <ContrastExamPercentage subtitle={subtitle} examId={params?.examId} examList={examList} />
                            {/* 对比考试百分比情况分析*/}
                            {/* 对比考试参数分析 */}
                            <ContrastExamParams subtitle={subtitle} examId={params?.examId} examList={examList} />
                            {/* 对比考试参数分析 */}
                            <KnowledgeComparisonAnalysis examId={params?.examId} subtitle={subtitle} examList={examList} />
                        </section>) : null}
                        <section className={styles.download}>
                            <Flex
                                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>

                        <section style={{ height: 32 }}></section>
                    </section>
                </Col>
            </Row>

            <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} allowClear onChange={(value, option) => {
                            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;