<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="item.value" :placeholder="'请选择' + item.name"
                        class="select_item" @change="ChangeFilters({ index: index, value: item.value })"
                        v-for="(item, index) in filterData" :key="index" v-show="item.list.length > 1">
                        <el-option v-for="item in item.list" :key="item.value" :label="item.label"
                            :value="item.value"></el-option>
                    </el-select>
                </div>
                <template v-if="isShowBtn">
                    <el-button size="medium" @click="downloadWrongQuestions(0)">下载错题本</el-button>
                    <el-button type="primary" size="medium" @click="downloadWrongQuestions(1)">下载个性化提升手册</el-button>
                </template>
            </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 class="mm_btn" :class="{ active: activeBtn === pathTwo }"
                                    @click="toPage(pathTwo)">个性化错题</button>
                            </div>
                            <div class="right">
                                <div class="page_filter" ref="filterContent">
                                    <FiltersItem :filtersData="filterData" @selectItem="ChangeFilters"></FiltersItem>
                                </div>
                                <router-view ref="child"></router-view>
                            </div>
                        </div>
                    </template>

                    <template v-else>
                        <div class="page_filter" ref="filterContent">
                            <FiltersItem :filtersData="filterData" @selectItem="ChangeFilters"></FiltersItem>
                        </div>
                        <router-view ref="child"></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;//监听改变滚动条参数 
        },
    },
    data() {
        return {
            isShowFilter: false, //是否显示筛选条件
            isShowBtn: false, //是否显示下载按钮
            filterData: [
                {
                    name: "科目名称",
                    value: '0',
                    type: "subjectName",
                    list: [], //选项
                }
            ],
            resizeTimer: null,
            activeBtn: this.$route.path,
            pathOne: '/studentAnalysisReport/reportDetails/scrolReport',
            pathTwo: '/studentAnalysisReport/reportDetails/personalWrongQuestions',
            isLianXiao: false,//是否联校
        };
    },

    created() {
        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为非总分
            };
            //设置是否是总分
            this.$store.commit("report/set_state", {
                key: "isTotalScore",
                value: courseObj.isTotal == 1 || courseObj.subjectGroupType == 1,//1为总分 0为非总分  1为组合科目 0为非组合科目
            });

            localStorage.setItem('reportExamCourseId', courseObj.subjectId);//单科的考试科目id
            localStorage.setItem('reportIsTotalScore', courseObj.isTotal == 1 || courseObj.subjectGroupType == 1)
            console.log("打印筛选数据", filterObject);
            this.$store.dispatch("report/UpdateFilterObject", filterObject);
        },

        // 滚动条事件
        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");
            }    
            
        },
    },
    watch: {
        '$route'(to, from) {
            this.ResetScroll();//重置滚动条
        },//路由变化 重置页面滚动条位置

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

    },
    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>
