<template>
    <!-- 分析报告详情总页面 -->
    <div class="analysis_main">
        <div :class="['main_header', { 'full_screen': isLianXiao }]" ref="mainHeader">
            <div class="header_left">
                <span class="back_button" @click="GoBack">
                    <i class="iconfont icon_return"></i>返回
                </span>
                <span class="header_title">{{ pageName }}</span>
            </div>
            <div class="header_right">
                <div class="select_list" v-if="isShowFilter">
                    <el-select style="width: 120px" v-model="filterData[index].value" :placeholder="'请选择' + item.name"
                        class="select_item" @change="ChangeFilters({ index: index, value: $event })"
                        v-for="(item, index) in filteredFilterData" :key="index" v-show="item.list.length > 1">
                        <el-option v-for="option in item.list" :key="option.value" :label="option.label"
                            :value="option.value"></el-option>
                    </el-select>
                </div>
                <template v-if="isShowBtn">
                    <el-button size="medium" :disabled="!canBtnClick"
                        @click="downloadWrongQuestions(0)">下载错题本</el-button>
                    <el-button :disabled="!canBtnClick" type="primary" size="medium"
                        @click="downloadWrongQuestions(1)">下载个性化提升手册</el-button>
                </template>
                <!-- <el-button v-if="isShowPadfBtn" style="margin-left: 10px;" size="medium" type="primary" :loading="stuPdfLoading" @click="StuDownloadPDF">下载PDF</el-button> -->
            </div>
        </div>

        <div class="main_content">
            <div class="content_right" ref="rightContent" @scroll="ScrollChange">
                <div :class="['content_right_scroll', { 'full_screen': isLianXiao }]" ref="contentRightScroll">
                    <template v-if="isLianXiao">
                        <div class="mm_body">
                            <div class="left">
                                <button class="mm_btn mb_10" :class="{ active: activeBtn === pathOne }"
                                    @click="toPage(pathOne)">成绩分析</button>

                                <button v-if="isShowKnowledgeButtons" class="mm_btn mb_10"
                                    :class="{ active: activeBtn === pathTwo }" @click="toPage(pathTwo)">举一反三</button>
                                <button class="mm_btn mb_10" :class="{ active: activeBtn === pathThree }"
                                        @click="toPage(pathThree)">个人画像</button>
                            </div>

                            <div class="right">
                                <div class="page_filter" ref="filterContent">
                                    <FiltersItem :filtersData="filteredFilterData" @selectItem="ChangeFilters">
                                    </FiltersItem>
                                </div>
                                <router-view ref="child" @isPdfDataLoadEnd="isPdfDataLoadEnd"
                                    @closePdfLoading="closePdfLoading"></router-view>
                            </div>
                        </div>
                    </template>

                    <template v-else>
                        <div class="page_filter" ref="filterContent">
                            <FiltersItem :filtersData="filteredFilterData" @selectItem="ChangeFilters"></FiltersItem>
                        </div>
                        <router-view ref="child" @isPdfDataLoadEnd="isPdfDataLoadEnd"
                            @closePdfLoading="closePdfLoading"></router-view>
                    </template>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import FiltersItem from "@/components/FiltersItem_ruoyan.vue";
export default {
    components: { FiltersItem },
    computed: {
        pageName() {
            // let examName = this.$store.state.report.examSelectItem.examName;
            // if (examName) {
            //   return examName.split("_")[0];
            // }
            return this.$store.state.report.examSelectItem.examName
        },
        updateScrollTop() {
            return this.$store.state.report.updateScrollTop;//监听改变滚动条参数 
        },
        isShowKnowledgeButtons() {
            // 从环境变量中获取基础URL，判断是否显示按钮
            return process.env.VUE_APP_BASE !== 'https://www.k12100.com';
        },
        // 判断是否为总分科目，用于控制个人画像按钮显示
        isTotalScore() {
            return this.$store.state.report.isTotalScore;
        },
        // 动态过滤筛选数据，在个人画像页面隐藏总分选项
        filteredFilterData() {
            // 检查当前是否在个人画像页面
            const isPersonalProfilePage = this.$route.path === '/studentAnalysisReport/reportDetails/personalProfile';
            
            if (!isPersonalProfilePage) {
                // 非个人画像页面，返回原始数据
                return this.filterData;
            }
            
            // 深拷贝原始数据，避免直接修改
            const updatedFilterData = JSON.parse(JSON.stringify(this.filterData));
            
            // 遍历筛选数据，找到科目名称筛选项
            updatedFilterData.forEach(filterItem => {
                if (filterItem.type === 'subjectName') {
                    // 过滤掉总分选项（isTotal为1或subjectGroupType为1的选项）
                    filterItem.list = filterItem.list.filter(item => item.isTotal !== 1 && item.subjectGroupType !== 1);
                }
            });
            
            return updatedFilterData;
        },
        canBtnClick() {
            return this.$store.state.question.canDownloanBtnClick;
        }
    },
    data() {
        return {
            isShowFilter: false, //是否显示筛选条件
            isShowBtn: false, //是否显示下载按钮
            isShowPadfBtn: false,//是否显示下载pdf按钮
            isPdfLoadEnd: false,//报告册数据是否加载完成
            filterData: [
                {
                    name: "科目名称",
                    value: '0',
                    type: "subjectName",
                    list: [], //选项
                }
            ],
            resizeTimer: null,
            activeBtn: this.$route.path,
            pathOne: '/studentAnalysisReport/reportDetails/scrolReport',
            pathTwo: '/studentAnalysisReport/reportDetails/personalWrongQuestions',
            pathThree: '/studentAnalysisReport/reportDetails/personalProfile',//个人画像
            isLianXiao: false,//是否联校
            stuPdfLoading: false,
            schoolId: this.$store.state.user.userInfo.id,
        };
    },

    created() {
        this.isShowPadfBtn = this.$route.path == '/studentAnalysisReport/reportDetails/scrolReport';
        const schoolType = sessionStorage.getItem('schoolType') || '1'; //1:单校 2:联校
        this.isLianXiao = schoolType === '2';

        if (this.$store.state.report.filterData.length > 0) {
            //有数据
            this.filterData = this.$store.state.report.filterData;
        }
        // 绑定 resize 事件
        window.addEventListener('resize', this.HandleWidthChange);
        this.$nextTick(() => {
            this.SetHeadWidth();
        })
    },

    methods: {
        toPage(type) {
            this.activeBtn = type;
            this.$router.push(type);
        },

        // 处理宽度变化的逻辑
        HandleWidthChange() {
            // 防抖：避免窗口 resize 时频繁触发（100ms 内只执行一次）
            clearTimeout(this.resizeTimer);
            this.resizeTimer = setTimeout(() => {
                this.SetHeadWidth();
            }, 100);
        },

        SetHeadWidth() {
            if (this.$refs.contentRightScroll) {
                let scrollDivWidth = 0;
                if (this.isLianXiao) {
                    scrollDivWidth = this.$refs.contentRightScroll.offsetWidth - 20;//联校
                } else {
                    scrollDivWidth = this.$refs.contentRightScroll.offsetWidth;
                }
                const headDiv = this.$refs.mainHeader;
                headDiv.style.width = `${scrollDivWidth}px`;
            }
        },

        // 筛选事件
        ChangeFilters(e) {

            this.filterData[e.index].value = e.value;
            // 选中科目数据
            let courseObj = this.filterData[0].list.find(item => item.value == this.filterData[0].value);
            let filterObject = {
                examLevel: courseObj.examLevel,//1-联考 2-单校
                contrastExamIds: courseObj.contrastExamIds,//多次考试任务对比ID，不包含当前任务ID	
                examId: courseObj.examId,//考试id	
                subjectCode: courseObj.subjectCode, //科目code
                subjectGroupType: courseObj.subjectGroupType, //是否为组合科目 1为组合科目 0为非组合科目
                subjectName: courseObj.subjectName,//科目名称
                isTotal: courseObj.isTotal //是否为总分科目 1为总分 0为非总分
            };
            //设置是否是总分
            const isTotal = courseObj.isTotal == 1 || courseObj.subjectGroupType == 1;//1为总分 0为非总分  1为组合科目 0为非组合科目
            this.$store.commit("report/set_state", {
                key: "isTotalScore",
                value: isTotal,
            });

            localStorage.setItem('reportExamCourseId', courseObj.subjectId);//单科的考试科目id
            localStorage.setItem('reportIsTotalScore', isTotal)
            this.$store.dispatch("report/UpdateFilterObject", filterObject);

            // 如果选择了总分且当前在个人画像页面，跳转到成绩分析页面
            if (isTotal && this.$route.path === '/studentAnalysisReport/reportDetails/personalProfile') {
                this.toPage(this.pathOne);
            }
        },

        // 滚动条事件
        ScrollChange() {
            const path = this.$route.path;

            let scrollTop = this.$refs.rightContent.scrollTop;
            if (path === '/studentAnalysisReport/reportDetails/scrolReport') {
                const filterContent = this.$refs.filterContent;
                let scrollHeight = 242;
                if (filterContent) {
                    scrollHeight = filterContent.clientHeight;
                }
                this.isShowFilter = (scrollTop >= scrollHeight);
                this.$store.commit("report/set_state", {
                    key: "isShowFilter",
                    value: this.isShowFilter,
                });
                if (this.$refs.child && typeof this.$refs.child.GetScrollTop === 'function') {
                    this.$refs.child.GetScrollTop(scrollTop);
                }
            }

            if (path === '/studentAnalysisReport/reportDetails/personalWrongQuestions') {
                this.isShowBtn = (scrollTop >= 250);
                if (this.$refs.child && typeof this.$refs.child.GetScrollTop === 'function') {
                    this.$refs.child.GetScrollTop(scrollTop);
                }
            }
        },
        //重置滚动条
        ResetScroll() {
            this.$nextTick(() => {
                if (this.$refs.rightContent) {
                    this.$refs.rightContent.scrollTop = 0;
                }
            })
        },

        downloadWrongQuestions(type) {
            this.$store.commit("question/SET_VARIANTION", type);
        },

        //返回按钮点击
        GoBack() {
            const schoolType = sessionStorage.getItem('schoolType');
            if (schoolType == 1) {//单校
                this.$router.push("/studentAnalysisReport/list");
            } else {//联校
                this.$router.push("/jointStudentAnalysisReport/list");
            }

        },
        StuDownloadPDF() {
            if (!this.isPdfLoadEnd) {
                return this.$message.warning('请稍等报告数据生成中！');
            }
            this.stuPdfLoading = true;
            this.$refs.child.DownloadPdf();
        },
        isPdfDataLoadEnd() {
            this.isPdfLoadEnd = true;
        },
        closePdfLoading() {
            this.stuPdfLoading = false;
        },

        // 处理筛选数据更新，在个人画像页面隐藏总分选项
        handleFilterDataUpdate() {
            // 检查当前是否在个人画像页面
            const isPersonalProfilePage = this.$route.path === '/studentAnalysisReport/reportDetails/personalProfile';
            
            if (isPersonalProfilePage) {
                // 深拷贝原始数据，避免直接修改props
                const updatedFilterData = JSON.parse(JSON.stringify(this.filterData));
                
                // 遍历筛选数据，找到科目名称筛选项
                updatedFilterData.forEach((filterItem, index) => {
                    if (filterItem.type === 'subjectName') {
                        // 过滤掉总分选项（isTotal为1的选项）
                        const nonTotalItems = filterItem.list.filter(item => item.isTotal !== 1 && item.subjectGroupType !== 1);
                        
                        // 检查当前选中的是否是总分选项
                        const currentSelected = filterItem.list.find(item => item.value === filterItem.value);
                        const isCurrentTotal = currentSelected && (currentSelected.isTotal === 1 || currentSelected.subjectGroupType === 1);
                        
                        // 如果当前选中的是总分选项且有其他选项，切换到第一个非总分选项
                        if (isCurrentTotal && nonTotalItems.length > 0) {
                            this.ChangeFilters({ index, value: nonTotalItems[0].value });
                        }
                    }
                });
            }
        },
    },
    watch: {
        '$route'(to, from) {
            this.ResetScroll();//重置滚动条
            this.handleFilterDataUpdate();
        },//路由变化 重置页面滚动条位置

        updateScrollTop: {
            handler(newVal) {
                this.ResetScroll();//重置滚动条
            },
        },

        // 监听筛选数据变化，动态过滤总分选项
        filterData: {
            deep: true,
            handler() {
                this.handleFilterDataUpdate();
            }
        }

    },
    beforeUnmount() {
        // 解绑事件，避免内存泄漏
        window.removeEventListener('resize', this.HandleWidthChange);
        // 清除计时器
        clearTimeout(this.resizeTimer);
    }
};
</script>

<style scoped lang="scss">
.mm_body {
    display: flex;
    width: 100%;
    justify-content: space-between;

    .left {
        width: 170px;
        padding: 20px;
        border-radius: 10px;
        background-color: #ffffff;
        height: fit-content;
        box-sizing: border-box;
        position: sticky;
        top: 0px;

        .mb_10 {
            margin-bottom: 10px;
        }
    }

    .right {
        width: calc(100% - 180px);
    }
}
</style>
