<template>
 <!-- 未扫描  缺考  已上传  列表页面  -->
  <div class="content_main">
    <div class="scan_content_left">
        <div class="right_tab_underline" v-if="scanState == 1">
            
            <div class="tab_item" :class="showUploadReview == 0?'tab_item_cur':''" @click="ChangeUploadShow(0)" >
                考生详情
            </div>
            <div class="tab_item" :class="showUploadReview == 1?'tab_item_cur':''" @click="ChangeUploadShow(1)">
                复查识别
            </div>
        </div>
        <div class="right_user_tab" v-else>
            <!-- 按考场 1  按班级 2 -->
            <div class="tab_system_user" :class="activeName == 1?'select_cur':''" @click="ChangeRoomType(1)" >
                按考场
            </div>
            <div class="tab_temporay_user" :class="activeName == 2?'select_cur':''" @click="ChangeRoomType(2)">
                按班级
            </div>
        </div>
        <div class="page_jg_20"></div>
        <div class="left_tree page_tree" v-if="markType==0 || showUploadReview==0">
            <el-tree  :highlight-current="true" class="filter-tree" :data="treeData" default-expand-all :props="defaultProps" :default-expanded-keys="defaultExKey" node-key="id" ref="classTree" @node-click="TreeHandleNodeClick"></el-tree>

        </div>
        <div v-else class="left_question">
            <!-- 手阅卡下拉列表 -->
            <div class="question_item" :class="reviewQuestionIndex=='objectiveIndex'?'question_item_cur':''" @click="ReviewObject()">
                客观题
            </div>
            <div class="question_item" :class="reviewQuestionIndex==item.subjectiveIndex?'question_item_cur':''" v-for="(item,index) in reviewQuestionList" :key="index" @click="ReviewChangeQuestion(item)">
                <div>  {{item.subjectiveName}} </div>
                <div>  {{item.subjectiveScore}}分 </div>
            </div>
        </div>
    </div>
    <!-- 列表界面 -->
    <div class="scan_content_right" v-if="showUploadReview == 0">
        <div class="right_search">
            <div class="search_input">
                <el-input type="text" v-model="keyWord" placeholder="学生姓名、考号" >
                    <el-button slot="append" icon="el-icon-search" ></el-button>
                </el-input>
            </div>
            <div class="search_button el_button">
                <el-button class="refresh_btn" @click="RefreshList()" ><i class="iconfont icon_shuaxin"></i>刷新</el-button>
                <el-button class="marke_miss_exam_btn" @click="AllMarkedMiss()" v-if="scanState == 0" >全部标缺</el-button>
                <el-button  class="refresh_btn" @click="ExportData()"><i class="iconfont icon_export" style="margin-right: 5px;"></i>导出</el-button>
                <el-button style="padding:0px 10px;"  @click="OpenReldentify()" v-if="scanState == 1">重新识别客观题</el-button>
                <el-button :class="multiSelection.length>0?'marke_normal_btn':'marke_normal_btn_disable'" @click="MarkStudent(0)"  v-if="scanState == 2" :disabled="!multiSelection.length">标记为正常</el-button>
                <el-button :class="multiSelection.length>0?'marke_anomaly_btn':'marke_anomaly_btn_disable'" @click="MarkCardNumberAbnormal()"  v-if="scanState == 1" :disabled="!multiSelection.length>0">标记为异常</el-button>
                <el-button :class="multiSelection.length>0?'delete_btn':'delete_btn_disable'"  @click="MarkStudent(4)" v-if="scanState == 1" :disabled=" !multiSelection.length"> 批量删除</el-button>
            </div>
        </div>
        <div class="page_table table_row_42" style="width: calc(100% - 40px); margin: auto;" v-loading="isLoading" element-loading-text="加载中……" element-loading-spinner="el-icon-loading" element-loading-background="#ffffff">
            <el-table ref="popupTable" :key="scanState" @select-all="SelectCheckAll" @selection-change="HandleSelectionChange"  :data="studentTableData" :height="tableHeight" stripe >
                <el-table-column align="center" type="selection" width="50" v-if="scanState != 0" ></el-table-column>
                <el-table-column align="center" type="index" width="50" label="序号" :index="HandleIndexMethod"></el-table-column>
                <el-table-column align="center" prop="studentBatch" label="扫描批次" v-if="scanState == 3"></el-table-column>  
                <el-table-column align="center" prop="studentCode" label="学号"></el-table-column>
                <el-table-column align="center" prop="examCode" label="考号"></el-table-column>
                <el-table-column align="center" prop="studentName" label="姓名"></el-table-column>
                <el-table-column align="center" prop="adminClassName" label="行政班"></el-table-column>
                <el-table-column align="center" prop="teachingClassName" label="教学班"></el-table-column>
                <el-table-column align="center" prop="registrationTypeName" label="学生类型"></el-table-column>
                <el-table-column align="center"  label="考场">
                    <template #default="scope">
                        <!-- 提的bug  沒没有考场显示行政班 -->
                        <span v-if="scope.row.examRoomName">{{scope.row.examRoomName}}</span>
                        <span v-else>{{scope.row.adminClassName}}</span>

                    </template>
                </el-table-column>
                <el-table-column align="center"  label="填涂标记" v-if="scanState==2">
                    <template #default="scope">
                        
                        <div class="miss_img" v-if="scope.row.paperUrl">
                        <img :src="scope.row.paperUrl"  alt="">
                        </div>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="scannedStatus" label="状态" key="scannedStatus">
                    <template #default="scope">
                        <div class="table_row_scan_state" v-if="scanState == 0">
                            <div class="state_no_scan"></div>未扫描
                        </div>
                        <div class="table_row_scan_state" v-if="scanState == 2">
                            <div class="state_miss_exam"></div>缺考
                        </div>
                        <div class="table_row_scan_state" v-if="scanState == 1">
                            <div class="state_success_upload"></div>已上传
                        </div>
                    </template>
                </el-table-column>
                
                
                <el-table-column align="center" label="操作" width="160" >
                    <template #default="scope">
                            <!-- 未扫描 -->
                        <div class="table_row_option" v-if="scanState == 0">
                            <span class="option_button_editor" @click="MarkToMiss(scope.row)">标记为缺考</span>
                        </div>
                        <!-- 缺考 -->
                        <div class="table_row_option" v-if="scanState == 2">
                            <span class="el_button_editor"  @click="OptionView(scope.row)" v-if="scope.row.paperUrl">查看</span>
                            <span class="option_button_editor"  @click="MarkToNormal(scope)">标记为正常</span>
                        </div>
                        <!-- 已上传 -->
                        <div class="table_row_option" v-if="scanState == 1">
                            <span class="el_button_editor"  @click="OptionView(scope.row)">查看</span>
                            <span class="el_button_delete" @click="UploadDelete(scope.row)">删除</span>
                        </div>
                    </template>
                </el-table-column>
                
            </el-table>
            <div class="page_pagination" v-show="studentList.length>10">
                <el-pagination
                    @current-change="ChangePage"
                    background
                    
                    :page-sizes="[10,50,100]"
                    layout="sizes,prev, pager, next"
                    @size-change="ChangePageSize"
                    :current-page="pageInfo.pageNum"
                    :total="pageInfo.total">
                </el-pagination>
            </div>
        </div>
    </div>
    <div class="scan_content_rights" v-else>
        <!-- 复查界面 -->
        <div class="rights_center page_search" v-if="showReviewType==0">

            <div class="center_search search_content" v-if="markType==1">
                <div class="content_left">
                    <div class="search_item">
                        班级：  
                        <el-select  v-model="reviewObjectClassCode" placeholder="请选择"  style="width: 120px;" @change="ChangeObjectClassCode()">
                            <el-option value="" label="全部班级"></el-option>
                            <el-option v-for="(item,index) in reviewObjectClassList" :key="index" :value="item.examRoomCode" :label="item.examRoomName"></el-option>
                        </el-select>
                        
                    </div>
                    
                </div>
                <div class="content_right">
                    <el-input type="text" style="width: 100%;" @keyup.enter.native="GetObjectSearchStudent" v-model="searchContent" @input="GetObjectSearchStudent" placeholder="学生姓名、考号" >
                        <el-button slot="append" icon="el-icon-search" style="width:68px;"  @click="GetObjectSearchStudent"></el-button>
                    </el-input>
                </div>
                
            </div>
            <div class="page_jg_20" v-if="markType==1">
            </div>
            <!-- 客观题复查 -->
            <div :class="markType==1?'center_image':'center_images'" >   
                <ActionImage ref="ActionCanvas" :isDrag="true" :paperInfo="currentPageInfo"  :paperImgUrl="currentImageUrl" :drawData="currentDrawData"></ActionImage>
            </div>
            
            <div class="left_bottom">
                <div class="bottom_draggable draggable_width_100" >
                    <!-- <draggable class="move_container" v-model="myArray"  chosenClass="chosen" forceFallback="true" group="people" animation="1000" > -->
                        <div v-for="(item,index) in studentPaperList" class="bottom_img_item"  :class="currentImageUrl == item.recognizeUrl?'img_item_cur':''" @click="StudentChanageCurrentPaperUrl(index, item)" :key="'paper_'+index">
                            
                            <img style="width: 100%;height: 100%" :src="item.recognizeUrl" alt="" >
                            
                            <div class="bottom_img_item_number">
                                <span v-if="item.pageNo>0">{{item.pageNo}}</span>
                                <span v-else></span>
                            </div>
                        </div>  
                    <!-- </draggable> -->
                </div>
            
            </div>
        </div>
        <!-- 主观题复查 -->
        <div class="rights_center page_search"  v-else>
            <div class="center_search search_content">
                <div class="content_left">
                    <div class="search_item">
                        班级：  
                        <el-select  v-model="reviewClassIdCode" placeholder="请选择"  style="width: 120px;" @change="ChangeScoreSearch()">
                            <el-option value="" label="全部班级"></el-option>
                            <el-option v-for="(item,index) in reviewClassList" :key="index" :value="item.value" :label="item.label"></el-option>
                        </el-select>
                        
                    </div>
                    <div class="search_item">
                        分数区间： 
                        <el-select  v-model="reviewMinScore" placeholder="请选择"  style="width: 100px;margin-right: 6px;"  @change="ChangeScoreSearch()">
                            <el-option v-for="(i,index) in scoreOptions" :key="index" :value="index" :label="i"></el-option>
                        </el-select>至
                        <el-select  v-model="reviewMaxScore" placeholder="请选择" style="width: 100px;margin-left: 5px;"  @change="ChangeScoreSearch()">
                            <el-option v-for="(i,index) in scoreOptions" :key="index" :value="index" :label="i"></el-option>
                        </el-select>
                    </div>
                </div>
                <div class="content_right">
                    <el-input placeholder="学生姓名、考号"  v-model="reviewKeyWord" @input="ChangeScoreSearch" @change="ChangeScoreSearch()" class="input_width">
                        <el-button @click="GetMarkReviewStudentList()"  slot="append" icon="el-icon-search"></el-button>
                    </el-input>
                </div>
            </div>
            <div class="center_list mark_score_center" ref="reviewList" v-loading="reviewLoading" element-loading-text="加载中……" element-loading-spinner="el-icon-loading" element-loading-background="#ffffff">
                <div class="center_item" :id="`student-${item.id}`" :class="reviewStudentId==item.id?'center_item_cur':''" v-for="(item,index) in reviewStudentList" :key="index">
                    <div class="item_header">
                        <div class="header_student_name">
                            <span>{{HandleIndexMethod(index)}}.{{item.studentName}} ({{item.exCode}})</span>
                            <span>{{item.adminClassName}}</span>
                            <span class="view_paper" @click="OptionScorePaper(item)">查看答题卡</span>
                        </div>
                        <div class="header_student_score">得分：{{item.score}}</div>
                    </div>
                    <div class="item_image">
                        <!-- <img :src="item.url" alt=""> -->
                        <!-- <MarkScore :drawData="reviewQuestionScoreList" :fullScore="reviewQuestionScore" :score="item.score" :paperImgUrl="item.url" @GetClickItem="(score) => GetClickItem(score,item, index)"></MarkScore> -->
                    </div>
                </div>
            </div>
            <div class="page_score_pagination" >
                <el-pagination
                    @current-change="ChangeReviewPage"
                    background
                    
                    :page-sizes="[20,50,100]"
                    layout="total,sizes,prev, pager, next"
                    @size-change="HandleSizeReviewChange"
                    :current-page="pageInfo.pageNum"
                    :total="pageInfo.total">
                </el-pagination>
            </div>
        </div>
        <div class="rights_right" v-if="showReviewType==0">
            <div class="page_jg_20" v-if="markType==0"></div>
            <div  class="right_search el_button" style="width: calc(100% - 40px); margin: auto;" v-if="markType==0">
                <el-input type="text" style="width: 100%;" @keyup.enter.native="GetObjectSearchStudent" v-model="searchContent" @input="GetObjectSearchStudent" placeholder="学生姓名、考号" >
                    <el-button slot="append" icon="el-icon-search" style="width:68px;"  @click="GetObjectSearchStudent"></el-button>
                </el-input>
                
            </div>
            <div class="page_jg_20"></div>
            <div class="right_table" ref="objectQuestionTables">   
                <el-table ref="studentTable" @row-click="RightStudentRowClick" :row-class-name="StudentTableClassName" :data="objectTableData" max-height="238" border >
                    <el-table-column align="center" type="index" label="序号" width="50">
                        
                    </el-table-column>  
                    <el-table-column align="center"  prop="studentName"   label="姓名" show-overflow-tooltip></el-table-column>
                    <el-table-column align="center" prop="examCode"  label="考号" show-overflow-tooltip></el-table-column>
                    <el-table-column align="center" width="50" prop="adminClassName"  label="班级"></el-table-column>
                </el-table>
                <div class="right_title">
                    <div>
                    客观题复查 <span @click="ClearValue()"  class="clear_value">清空</span>
                    </div> 
                </div>
            </div>
            <div class="answer_table">
                <el-table :data="currentQuestionList" :height="objectTableHeights" border  :row-class-name="ObjectTableClassName" :key="tableKey" >
                    <el-table-column align="center" prop="objectiveName" label="题号" width="90"></el-table-column>  
                    <el-table-column align="center" prop="studentName"  label="选项">
                        <template v-slot="scope">
                            <div class="table_row_answer_choose" v-if="scope.row.questionType==3">
                                <!-- 判断题 -->
                                <div class="answer_item" @click="ChooseAnswer(scope.row,GetLetterToNumberTF(item))" :class="IsCunzai(scope.row.selectValue,GetLetterToNumberTF(item))?'choose':''" v-for="(item,index) in scope.row.optionNum" :key="index">
                                    {{GetLetterToNumberTF(item)}}
                                </div>
                            </div>
                            <div class="table_row_answer_choose" v-else>
                                <div class="answer_item" @click="ChooseAnswer(scope.row,GetLetterToNumber(item))" :class="IsCunzai(scope.row.selectValue,GetLetterToNumber(item))?'choose':''" v-for="(item,index) in scope.row.optionNum" :key="index">
                                    {{GetLetterToNumber(item)}}
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                </el-table> 
            </div>
            <div class="right_button el_button">
                <div class="bottom_button_item">
                    <!-- <el-button @click="MarkPositionAbnormal" class="abnormal_other_btn">标记定位异常</el-button> -->
                    <el-button @click="StudentObjectiveCheck" class="re_cut_btn_100">校正完成</el-button>
                </div>
            </div>
        </div>
        <div class="rights_right" v-else>
            <!-- 主观题校正 -->
            <div class="page_jg_20"></div>
            <div class="answer_table">
                <el-table ref="subjectReviewTable" :data="reviewStudentList" :height="subjectReviewTableHeight" border  :row-class-name="ObjectTableClassName" :key="tableKey" >
                    <el-table-column align="center" type="index" label="序号" width="60">
                        <template slot-scope="scope">
                            <span v-text="HandleIndexMethod(scope.$index)"></span>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="studentName"  label="姓名">

                    </el-table-column>
                    <el-table-column align="center" prop="score"  label="得分">
                        <template v-slot="scope">
                            <el-input v-model="scope.row.score" @focus="ScoreFocus(scope.row)" :class="parseFloat(scope.row.score)>parseFloat(reviewQuestionScore)?'input_error':''" placeholder=""  maxlength="5"></el-input>
                        </template>
                    </el-table-column>
                </el-table> 
            </div>
            <div class="right_button el_button">
                <div class="bottom_button_item">
                    <!-- <el-button @click="MarkPositionAbnormal" class="abnormal_other_btn">标记定位异常</el-button> -->
                    <el-button @click="SubjectiveReviewCheck()" :loading="correctionLoading" class="re_cut_btn_100">校正完成</el-button>
                </div>
            </div>
        </div>
    </div>
    <div class="page_dialog">
        <ReIdentify v-model="isReIdentify" :reIdentifyTotal="reIdentifyTotal" justObjective="1" :schoolInfo="selectSchoolInfo"  @ReIdentifyComplete="RefreshList"></ReIdentify>
        <PaperPreview v-model="showPaperPreview" :imageList="previewImageList" :showDraw="true" :answerData="previewAnswerData"></PaperPreview>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { useExamStore } from '@/store/exam'
import { useUserStore } from '@/store/user'
import { useRouter } from 'vue-router'
import { onMounted ,ref,nextTick,onUnmounted,computed, watch} from 'vue';
import {deleteAnswerCard, getExamStudentList,updateScannedStatus,updateExamNumberException,correctObjectiveQuestion,getTemplateDetail } from '@/api/exam';
import { ElMessageBox, ElMessage } from 'element-plus'
import PaperPreview from '../components/PaperPreview.vue'//图片预览组件
import ActionImage from '@/components/ActionImage.vue'// 画布图片组件
import ReIdentify from '@/views/exam/components/ReIdentify.vue';//重新识别弹窗
// 实例化 Store
const examStore = useExamStore()
const userStore = useUserStore()
const router = useRouter()

// 定义 Props
const props = defineProps({
  
  scanState: {
    type: Number,
    default: 0,
  }, // 状态 状态  0  未扫描  1 已上传 2  缺考  3 异常
  showTool: {
    type: Boolean,
    default: false,
  }, // 是否显示工具栏
  showDraw: {
    type: Boolean,
    default: false,
  }, // 是否显示绘图框
  answerData: {
    type: Object,
    default: () => ({}),
  }, // 答案
})

//监听props变化
watch(() => props.scanState, (newState) => {

    console.log("扫描状态变更为",newState);
    pageInfo.value.pageNum=1;
    showUploadReview.value=0;
    GetExamStudentList();//获取考生列表
});

// 考试科目 ID
const examSubjectId = computed(() => {
  return examStore.currentExam?.id
})//计算属性

//考试科目code
const examSubjectCode=computed(() => {
    return examStore.currentExam?.examSubjectCode
})
//当前登录人姓名
const currentUserName=computed(() => {
    return userStore.userName;
})


/**
 * 客观题表格学生数据（带搜索过滤）
 * @description 根据搜索关键词过滤学生列表，支持姓名和考号的模糊匹配
 */
const objectTableData = computed(() => {
    // 如果没有搜索内容，返回完整的学生列表
    if (!searchContent.value || searchContent.value.trim() === '') {
        return studentList.value;
    }
    
    // 将搜索内容转为小写，实现不区分大小写的搜索
    const searchLower = searchContent.value.toLowerCase();
    
    // 过滤学生列表
    return studentList.value.filter((student: any) => {
        // 匹配姓名（不区分大小写）
        const nameMatch = student.studentName?.toLowerCase().includes(searchLower);
        
        // 匹配考号（转为字符串后匹配）
        const codeMatch = student.exCode?.toString().toLowerCase().includes(searchLower);
        
        // 任一条件满足即返回
        return nameMatch || codeMatch;
    });
});

const showUploadReview = ref(0)//0 考生详情  1 复查识别
const schoolId=ref(0);//默认0  后面联考在调整
const showReviewType=ref(0);//复查题目类型 0-客观题 1-主观题

const activeName = ref(1);//1 按考场 2 按班级
const markType=ref(0)//0 网阅卡 1 手阅卡
const reviewQuestionIndex=ref('');//当前选择的题目索引
const showPaperPreview=ref(false);//预览试卷
const previewImageList=ref<any[]>([]);//图片列表
const previewAnswerData=ref<any[]>([]);//答案数据
const currentTemplateList=ref<any[]>([]);//模板数据

// 客观题重新识别
const isReIdentify=ref(false);//打开重新识别弹窗
const reIdentifyTotal=ref(0);//重新识别的总张数
const selectSchoolInfo=ref({
    schoolId:'',
    schoolName:''
});//学校信息
// 修改后：显式声明类型为 any[]，或者定义具体的 Interface
interface TreeNode {
  id: string | number;
  label: string;
  children?: TreeNode[];
  studentList?: any[];
  [key: string]: any; // 允许其他属性
}

const treeData = ref<TreeNode[]>([]); // 树形结构数据
const defaultExKey=ref(['all']);//
const selectNodeId=ref('all');//选择的节点id
const defaultProps={
    children: 'children',
    label: 'label'
};

const keyWord=ref('');//搜索关键词
const reviewKeyWord=ref('');//复查搜索关键词

const multiSelection=ref([]);//多选数据
const isLoading=ref(false);//表格加载状态
// 学生表格数据（前端分页处理）
const studentTableData = computed(() => {

  if(keyWord.value=='')
  {
    const start = (pageInfo.value.pageNum - 1) * pageInfo.value.pageSize;
    const end = start + pageInfo.value.pageSize;
    return studentList.value.slice(start, end);
  }
  else
  {
    return studentList.value.filter(student=>{
        return (
            student.studentName.toLowerCase().includes(keyWord.value.toLowerCase()) 
            ||
            student.exCode.toLowerCase().includes(keyWord.value.toLowerCase())
        );
    })
  }
  
});

const  studentPaperList= computed(() => {

    const list = currentPaperList.value;
        // 如果列表为空或未定义，返回空数组
    if (!list || list.length === 0) {
        return [];
    }
    // 按照 pageNo 升序排序并返回新数组
    return list;
});//学生试卷列表

const pageInfo=ref({ pageNum: 1, pageSize: 20, total: 0 });//分页信息

const allStudentList=ref([]);//所有学生列表数据存储
const studentList=ref<any[]>([]);//学生列表数据

const reviewObjectClassCode=ref('');//班级代码
const reviewObjectClassList=ref([]);//班级列表
const searchContent=ref('');//搜索内容
const currentImageUrl=ref('');//当前试卷图片url
const rotationAngle = ref(0); // 旋转角度
const currentQuestionPositionData = ref<any[]>([]); ////客观题点位数据  暂未用上 后面可能舍弃

const currentPageInfo=ref({});//当前试卷页面信息
const reviewClassIdCode=ref('');//班级代码
const reviewClassList=ref([]);//班级列表
const reviewMinScore=ref('');//分数区间最小值
const reviewMaxScore=ref('');//分数区间最大值
const scoreOptions=ref([]);//分数选项
const reviewLoading=ref(false);//复查加载状态

const reviewStudentList=ref([]);//复查学生列表
const tableHeight=ref(200);//学生表格高度
const subjectReviewTableHeight=ref(200);//主观题复查表格高度
const objectTableHeights=ref([200]);//客观题复查表格高度
const tableKey=ref(0);//表格key

// 添加缺失的响应式变量

const currentItem = ref<any>(null); // 当前选中的学生项
const currentIndex = ref(-1); // 当前选中学生的索引
const currentPaperList = ref<any[]>([]); // 当前学生的试卷列表
const currentPaperNumber = ref(1); // 当前图片页码
const currentQuestionList = ref<any[]>([]); // 当前题目列表
const currentDrawData = ref<any[]>([]); // 当前绘图数据
const objectPageNumber = ref(1); // 客观题页码

// 添加 DOM 引用
const objectQuestionTables = ref<HTMLElement | null>(null); // 客观题表格区域引用
const studentTable = ref<any>(null); // 学生表格引用   
const classTree=ref<any>(null); //班级树引用

//全部标缺
const AllMarkedMiss=async()=>{
    if(studentList.value.length==0)
    {
        return;
    }

    // 1. 增加二次确认弹窗
    await ElMessageBox.confirm(
        `确定要将当前列表下的 ${studentList.value.length} 名学生全部标记为缺考吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    );
    let studentScanIds=[];
    for(let i=0;i<studentList.value.length;i++)
    {
        studentScanIds.push(studentList.value[i].id);   
    }
    UpdateScanStatus(studentScanIds,2);//修改状态 0 未扫描 1 已上传 2  缺考  3 异常   0-未扫描 2-缺考(修改时传，删除不传)
    

}

//重新识别客观题
const OpenReldentify=()=>
{
    isReIdentify.value=true;
    reIdentifyTotal.value=studentList.value.length;

}

//刷新列表
const RefreshList=()=>{
    GetExamScanList();
}

/**
 * 已上传客观题复查 - 图片切换事件
 * @param index - 图片在列表中的索引
 * @param item - 被点击的图片对象（包含 recognizeUrl 和 pageNo）
 * @description 切换当前显示的试卷图片，并重置相关状态
 */
const StudentChanageCurrentPaperUrl = (index: number, item: any) => {
    console.log("切换图片索引:", index);
    console.log("切换的图片对象:", item);  
    console.log("当前图片列表数据:", currentPaperList.value);
    
    // 重置旋转角度
    rotationAngle.value = 0;
    
    // 更新当前显示的图片URL
    currentImageUrl.value = item.recognizeUrl;
    
    // 更新当前页码
    currentPaperNumber.value = item.pageNo;
    
    // 清空题目位置数据
    currentQuestionPositionData.value = [];
    
    // 重新处理客观题答案回显
    ObjectDataChange();
}



//客观题复查识别查询学生
const GetObjectSearchStudent = () => {
    console.log("打印搜索结果tableData", objectTableData.value);
    
    if (objectTableData.value.length > 0) {
        currentItem.value = objectTableData.value[0];
        currentIndex.value = objectTableData.value.findIndex(item => item.id == currentItem.value.id);
        currentPaperList.value = currentItem.value.scanPictureVOS || [];
        currentPaperNumber.value = objectPageNumber.value; // 当前图片的页码
        
        // 查找对应页码的图片URL
        const targetPage = currentPaperList.value.find((item: any) => item.pageNo == currentPaperNumber.value);
        currentImageUrl.value = targetPage ? targetPage.recognizeUrl : '';
        
        // 深拷贝客观题列表，避免直接修改原数据
        currentQuestionList.value = JSON.parse(JSON.stringify(currentItem.value.objectiveQuestionVOS || []));
        
        // 调用客观题数据处理方法
        ObjectDataChange();
        
        console.log("打印搜索结果", studentList.value);
    } else {
        currentItem.value = null;
        currentPaperList.value = [];
        currentPaperNumber.value = 1;
        currentImageUrl.value = '';
        currentQuestionList.value = [];
        currentDrawData.value = [];
    }
}


// 学生表格行样式类名
const StudentTableClassName = ({ row }: { row: any }) => {
    if (currentItem.value && row.id == currentItem.value.id) {
        return 'selected_row';
    } else {
        return '';
    }
}

//// 检查当前行是否为异常题目
const ObjectTableClassName = ({ row, rowIndex }: any) => { 

    if(row.hasAbnormal==1)
    {
            console.log("客观题异常hasAbnormal的列是",row.objectiveName);
        //异常的背景显示红色
            return 'selected_row';
    }
    else
    {
        return '';
    }
}

// 已上传的表格点击事件
const RightStudentRowClick = (item: any) => {
    console.log("打印选择的数据", item);
    currentItem.value = item;
    currentIndex.value = studentList.value.findIndex((stu: any) => stu.id == currentItem.value.id);
    currentPaperList.value = currentItem.value.scanPictureVOS || [];
    currentPaperNumber.value = objectPageNumber.value; // 当前图片的页码
    
    // 查找对应页码的图片URL，添加安全检查
    const targetPage = currentPaperList.value.find((page: any) => page.pageNo == currentPaperNumber.value);
    currentImageUrl.value = targetPage ? targetPage.recognizeUrl : '';
    
    // 深拷贝客观题列表，避免直接修改原数据
    currentQuestionList.value = JSON.parse(JSON.stringify(currentItem.value.objectiveQuestionVOS || []));
    previewAnswerData.value={ ...item.objectiveMaps, ...item.selectiveMaps };
    console.log('当前答案数据列表:', previewAnswerData.value);
    // 调用客观题数据处理方法
    ObjectDataChange();
}


// 5. 客观题答案回显数据设置切换  客观题数据处理 客观题回显
const ObjectDataChange = () => {
    // TODO: 根据 isShowDrawType 重新渲染右侧列表或 Canvas
    console.log('客观题答案回显', )
    console.log("打印模板数据",currentTemplateList.value);
    let questionList=currentTemplateList.value[0].examCardGroupVOS;//选择题判分就一页 
    console.log("打印客观题模板数据",questionList);
    const drawList: any[] = [];
    questionList.forEach((item:any, index:number) => {

        console.log("打印第"+index+"个切块数据",item);
        if (item.position) {
            let position = JSON.parse(item.position);
            let unit = 'px';//默认px单位
            let topiclist = [];
            if(item.groupTopicList)
            {
                //处理答案数据
                item.groupTopicList.forEach((topic:any) => {
                    let answerItem=currentQuestionList.value.find(questionItem => questionItem.objectiveName == topic.topicName);
                    // const answerValue = previewAnswerData.value[topic.topicName];//答案
                    console.log("打印topic",topic);
                    console.log("打印currentQuestionList", currentQuestionList.value);
                    console.log("打印answerItem",answerItem);
                    let answerList=JSON.parse(topic.optionJsons);
                    console.log("打印answerList",answerList);
                    topic.answerList=answerList;
                    if(answerItem)
                    {
                        if(answerItem.selectValue)
                        {
                                // 将多个字母拆分成数组
                            // const answerLetters = answerItem.selectValue.split('');
                            // 将多个字母拆分成数组（兼容多种分隔符）
                            const answerLetters = answerItem.selectValue.match(/[A-Za-z]/g) || [];
                            // console.log('answerLetters',answerLetters);
                            answerLetters.forEach((letter:any) => {
                                let answerIndex = GetAnswerIndexToLetter(letter);
                                if(topic.topicType==3)
                                {
                                    //判断题
                                    answerIndex=GetAnswerIndexToLetterTF(letter);
                                }
                                
                                console.log("打印answerIndex", answerIndex);
                                if (answerIndex !== -1 && topic.answerList[answerIndex]) {
                                    topic.answerList[answerIndex].isCheck = true;
                                }
                            });
                        }

                        if(answerItem.hasAbnormal==1)
                        {
                            //异常的背景显示红色
                            topic.hasAbnormal=true;//是否异常

                        }
                        
                    }
                });
                item.groupTopicList[0].answerList
                topiclist=item.groupTopicList;
            }

            var obj = {
                x: position.x,
                y: position.y,
                w: position.w,
                h: position.h,
                position: item.position,
                blockArea: 8,
                page: 1,//选择题就一页 默认1
                blockName: item.name,
                id: item.groupId,
                unit: unit,//单位
                usedCardType:2,//默认三方卡 选择题,
                areaOption: item.groupConfig,//添加选择题设置信息
                topiclist: topiclist,
            };
            // 1 全部区域  2 定位区 3 标题区 4 学号区 5 姓名区 6 缺考区 7 AB卷区 8 客观题区 9 选做题区
        

            drawList.push(obj);
        }
    });
    currentDrawData.value=drawList;
    console.log("打印客观题画框数据",currentDrawData.value);

}

//获取模板详情
const GetTemplateDetail = async () => { 
    const params={
        examSubjectId: examSubjectId.value,//考试id
    };
    const res = await getTemplateDetail(params);
    console.log("打印模板数据",res);
    if(res.code == 200)
    {
       currentTemplateList.value=[];
       res.data.forEach((item:any)=>{ 
        let obj={
            examCardGroupVOS: item.examCardGroupVOS,
            pageNo: item.pageNo,
            paperInfo: item.paperInfo,
            templateUrl: item.templateUrl,
            pageNum: item.pageNo,

        };
        currentTemplateList.value.push(obj);
       
       })
       


    }
    else
    {

    }
}


/**
 * 已上传复查校正 - 客观题校正完成
 * @description 保存当前学生的客观题校正结果，并自动切换到下一个学生
 */
const StudentObjectiveCheck = async () => {
    console.log("当前选择的校正数据:", currentQuestionList.value);
    console.log("当前选择的学生:", currentItem.value);
    
    // 判断数据是否和之前的一致，如果一致不调用接口
    const hasChanged = JSON.stringify(currentQuestionList.value) !== 
                       JSON.stringify(currentItem.value.objectiveQuestionVOS);
    
    if (hasChanged) {
        // 数据有改变，调用接口更新
        const params = {
            id: currentItem.value.id,
            objectiveQuestionDTOS: currentQuestionList.value
        };
        
        console.log("校正客观题参数:", params);
        
        try {
            const res = await correctObjectiveQuestion(params);
            console.log("校正结果:", res);
            if (res.code === 200) {
                ElMessage.success('校正成功');
                
                // 切换到下一个学生
                MoveToNextStudent();
                
                // 刷新列表数据
                GetExamScanList();
            } else {
                ElMessage.error(res.msg || '校正失败');
            }
        } catch (error) {
            console.error("校正客观题错误:", error);
            ElMessage.error('网络请求失败');
        }
    } else {
        // 数据未改变，直接切换到下一个学生
        const canMoveNext = MoveToNextStudent();
        
        if (!canMoveNext) {
            ElMessage.warning('已经是最后一个学生了哦!');
        }
    }
    
    // 滚动到当前行
    ScrollToCurrentRow();
}

/**
 * 清空所有客观题的答案值
 * @description 遍历当前题目列表，将所有题目的选中值重置为空，并触发视图更新
 */
const ClearValue = () => {
    // 遍历题目列表，清空每个题目的选中值
    currentQuestionList.value.forEach((item: any) => {
        item.selectValue = '';
    });
    
    // 构建答案对象：{ 题号: 答案 }
    const answerObj = currentQuestionList.value.reduce((acc: any, item: any) => {
        acc[item.objectiveName] = item.selectValue || '';
        return acc;
    }, {});
    
    console.log("清空后的答案对象:", answerObj);

    // 调用客观题数据处理方法，更新画框显示（清除所有选中状态）
    ObjectDataChange();
}


/**
 * 自动滚动到表格的当前行
 * @description 在学生表格中自动滚动并高亮显示当前选中的学生行
 */
const ScrollToCurrentRow = () => {
    nextTick(() => {
        // 使用 Element Plus 的 setCurrentRow 方法高亮选中行
        if (studentTable.value) {
            studentTable.value.setCurrentRow(currentItem.value);
        }
        
        // 获取表格 body 容器
        const tableBody = studentTable.value?.$el?.querySelector('.el-table__body-wrapper');
        
        if (tableBody && currentItem.value) {
            // 计算选中行的位置
            const rowIndex = studentList.value.findIndex(
                (student: any) => student.id === currentItem.value.id
            );
            
            if (rowIndex !== -1) {
                // 每行高度假设为 40px（可根据实际 CSS 调整）
                const rowHeight = 40;
                
                // 计算需要滚动到的位置（居中显示）
                const scrollTop = rowIndex * rowHeight - (tableBody.clientHeight / 2);
                
                // 滚动到指定位置，确保不小于 0
                tableBody.scrollTop = Math.max(0, scrollTop);
                
                console.log(`滚动到第 ${rowIndex + 1} 行，scrollTop: ${tableBody.scrollTop}`);
            }
        }
    });
}

/**
 * 切换到下一个学生
 * @returns {boolean} 是否成功切换
 * @description 将 currentIndex +1，如果超出范围则返回 false
 */
const MoveToNextStudent = (): boolean => {
    // 边界检查：避免数组越界
    if (currentIndex.value < studentList.value.length - 1) {
        currentIndex.value = currentIndex.value + 1;
        LoadStudentData(currentIndex.value);
        return true;
    } else {
        console.log("已经是最后一个学生");
        return false;
    }
}

/**
 * 加载指定索引的学生数据
 * @param index - 学生在列表中的索引
 * @description 根据索引加载学生的试卷图片、客观题数据等
 */
const LoadStudentData = (index: number) => {
    currentItem.value = studentList.value[index];
    currentPaperList.value = currentItem.value.scanPictureVOS || [];
    currentPaperNumber.value = objectPageNumber.value; // 当前图片的页码
    
    // 查找对应页码的图片URL，添加安全检查
    const targetPage = currentPaperList.value.find(
        (page: any) => page.pageNo === currentPaperNumber.value
    );
    currentImageUrl.value = targetPage ? targetPage.recognizeUrl : '';
    
    // 深拷贝客观题列表，避免直接修改原始数据
    currentQuestionList.value = JSON.parse(
        JSON.stringify(currentItem.value.objectiveQuestionVOS || [])
    );
    console.log('打印当前题目的列表currentQuestionList', currentQuestionList.value);
    // 调用客观题数据处理方法
    ObjectDataChange();
}

// 根据字母转换成索引
const GetAnswerIndexToLetter = (value: string) => {
    const letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 
           'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    return letters.findIndex(letter => letter == value);
}

// 判断题的
const GetAnswerIndexToLetterTF = (value: string) => {
    const letters = ['T', 'F'];
    return letters.findIndex(letter => letter == value);
}


//根据数字转换为字母
const GetLetterToNumber= (num: number): string => {

    const letters = ['', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 
            'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    return letters[num] || '';
}

/**
 * 将数字转换为判断题选项字母（T/F）
 * @param num - 选项索引（1-T, 2-F）
 * @returns 对应的字母（T 或 F），如果索引无效则返回空字符串
 */
const GetLetterToNumberTF = (num: number): string => {
    const letters = ['', 'T', 'F'];
    return letters[num] || '';
}

/**
 * 客观题异常处理 - 更改答案事件
 * @param item - 当前题目对象
 * @param answer - 被点击的答案选项（字母）
 * @description 处理多选题的答案选择/取消逻辑，支持切换选中状态
 */
const ChooseAnswer = (item: any, answer: string) => {
    console.log("选择的答案:", answer);
    console.log("选择的题目:", item);
    
    // 获取当前已选答案数组
    let answers = GetAnswerArray(item.selectValue);
    console.log("当前已选答案数组:", answers);
    
    // 查找答案在数组中的索引
    const index = answers.indexOf(answer);
    
    if (index > -1) {
        // 如果已存在，则移除（取消选中）
        answers.splice(index, 1);
        console.log(`取消选中答案: ${answer}`);
    } else {
        // 否则添加（选中）
        answers.push(answer);
        console.log(`选中答案: ${answer}`);
    }
    
    // 更新回 item.selectValue，并排序后拼接成字符串
    item.selectValue = answers.sort().join(',');
    console.log("更新后的 selectValue:", item.selectValue);
    
    // 构建答案对象：{ 题号: 答案 }
    const answerObj = currentQuestionList.value.reduce((acc: any, question: any) => {
        acc[question.objectiveName] = question.selectValue || '';
        return acc;
    }, {});
    
    console.log("新的答案对象:", answerObj);
    
    // 如果需要保存到其他数据结构，可以在这里处理
    // objectData.value.jsonObj = JSON.stringify(answerObj);
    
    // 调用客观题数据处理方法，更新画框显示
    ObjectDataChange();
}

/**
 * 检查答案字符串中是否包含指定选项
 * @param str - 答案字符串（如 "A,B,C"）
 * @param value - 要检查的选项值（如 "A"）
 * @returns {boolean} 如果包含则返回 true，否则返回 false
 * @description 用于判断某个选项是否已被选中
 */
const IsCunzai = (str: string, value: string): boolean => {
    // 安全检查：如果字符串为空或未定义，直接返回 false
    if (!str) {
        return false;
    }
    // 使用 includes 方法检查是否包含指定值
    return str.includes(value);
}

/**
 * 将答案字符串转换为数组
 * @param selectValue - 答案字符串（如 "A,B,C" 或 "A" 或 ""）
 * @returns 答案数组（如 ["A", "B", "C"] 或 ["A"] 或 []）
 * @description 兼容多种分隔符和空值情况
 */
const GetAnswerArray = (selectValue: string): string[] => {
    if (!selectValue || selectValue.trim() === '') {
        return [];
    }
    // 支持多种分隔符：逗号、空格、分号等
    return selectValue
        .split(/[,\s;]+/)  // 按逗号、空格、分号分割
        .map(s => s.trim()) // 去除空白
        .filter(s => s.length > 0); // 过滤空字符串
}



//查看已上传的图片
const OptionView=(item:any)=>{ 
    console.log("查看已上传的图片",item);
    //正常显示答题卡弹窗
    if(item.scanPictureVOS)
    {
        
        previewImageList.value=[];
        item.scanPictureVOS.forEach((image:any)=>{
            let obj={
                url:image.recognizeUrl,
                pageNo:image.pageNo,//页面页码
            };
            previewImageList.value.push(obj);
        });
        console.log("查看已上传的图片",item);
        // 合并两个对象
        previewAnswerData.value= { ...item.objectiveMaps, ...item.selectiveMaps };
        console.log("查看已上传的图片答案数据",previewAnswerData.value);
        showPaperPreview.value=true;

    }
    else
    {
       ElMessage.warning("未找到图片");
    }
}

/**
 * 已上传删除 - 实际为修改状态为未扫描
 * @param item - 要删除的学生对象
 * @description 调用删除接口移除学生的答题卡数据，并刷新列表
 */
const UploadDelete = async (item: any) => {
    try {
        // 显示确认对话框
        await ElMessageBox.confirm('是否要删除此条数据？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            closeOnClickModal: false,
            type: 'warning',
            customClass: 'page_dialog'
        });
        
        // 构建请求参数
        const param = {
            ids: [item.id],
            examSubjectId: examSubjectId.value,
            schoolId: schoolId.value
            // scannedStatus: 2, // 扫描状态 0-未扫描 2-缺考(修改时传，删除不传)
        };
        
        console.log("删除参数:", param);
        
        // 调用删除接口
        const res = await deleteAnswerCard(param);
        
        if (res.code === 200) {
            ElMessage.success('删除成功');
            
            // 刷新列表数据
            GetExamScanList();
        } else {
            ElMessage.error('删除失败！' + (res.msg || '未知错误'));
        }
    } catch (error) {
        // 用户点击取消或发生错误
        if (error !== 'cancel') {
            console.error("删除操作错误:", error);
            ElMessage.error('操作失败');
        }
    }
}


//单个标缺
const MarkToMiss=(item:any)=>{ 
    console.log("打印选择的学生数据",item);
    ElMessageBox.confirm(
        `确定要将 ${item.studentName} 标记为缺考吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 确定按钮点击事件处理
        let studentScanIds=[];
        studentScanIds.push(item.id);   
        UpdateScanStatus(studentScanIds,2);//修改状态 0 未扫描 1 已上传 2  缺考  3 异常   0-未扫描 2-缺考(修改时传，删除不传)
    }).catch(() => {
        // 取消按钮点击事件处理
    });

}

//标记状态
const MarkStudent=(status:number)=>{ 
    console.log("打印选择的学生数据",multiSelection.value);
    if(multiSelection.value.length==0)
    {
        ElMessage.warning("请选择需要操作的学生");
        return;
    }
    let statusStr=status==2?'缺考':'正常';

    //二次弹窗提示
    ElMessageBox.confirm(
        `确定要将选择的 ${multiSelection.value.length} 名学生标记为${statusStr}吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 确定按钮点击事件处理
        let studentScanIds=[];
        for(let i=0;i<multiSelection.value.length;i++)
        {
            studentScanIds.push(multiSelection.value[i].id);   
        }
        UpdateScanStatus(studentScanIds,status);//修改状态 0 未扫描 1 已上传 2  缺考  3 异常   0-未扫描 2-缺考(修改时传，删除不传)
    })

}

//标记考号异常
const MarkCardNumberAbnormal=()=>{ 
    ElMessageBox.confirm(
        `确定要将选择的 ${multiSelection.value.length} 名学生标记为考号异常吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 确定按钮点击事件处理
        let studentScanIds=[];
        for(let i=0;i<multiSelection.value.length;i++)
        {
            studentScanIds.push(multiSelection.value[i].id);   
        }
        const params={
            examSubjectId:examSubjectId.value,
            studentScanIds:studentScanIds,
        };
        updateExamNumberException(params).then((res)=>{
            if(res.code==200)
            {
                ElMessage.success("操作成功")
                GetExamStudentList();
            }
            else
            {
                ElMessage.error(res.msg)
            }
        })
        
    })
}


//修改学生状态
const UpdateScanStatus=async( studentIds:any, status:number )=>{
    
    const params={
        examSubjectId:examSubjectId.value,
        ids:studentIds,
        scannedStatus:status,//0 未扫描 1 已上传 2  缺考  3 异常   0-未扫描 2-缺考(修改时传，删除不传)
    };
    let res=await updateScannedStatus(params);
    console.log("批量修改状态返回结果",res);
    if(res.code==200)
    {
        ElMessage.success("操作成功")
        GetExamStudentList();
    }
    else
    {
        ElMessage.error(res.msg)
    }
}

const SelectCheckAll=()=>{

}
const HandleSelectionChange=(selection:any)=>{
    console.log("打印选中的数据",selection);
    multiSelection.value=selection;
}

//树形菜单切换事件
const TreeHandleNodeClick=(node:any)=>{
    console.log("树节点点击:", node);
    
    // 更新选中的节点ID和学生列表
    selectNodeId.value = node.id;
    studentList.value = node.studentList || [];
    
    // 重置分页信息
    pageInfo.value.total = studentList.value.length;
    pageInfo.value.pageNum = 1;
    
    // 如果没有学生数据，清空相关状态并返回
    if (studentList.value.length === 0) {
        currentItem.value = null;
        currentIndex.value = -1;
        currentPaperList.value = [];
        currentImageUrl.value = '';
        currentQuestionList.value = [];
        currentDrawData.value = [];
        return;
    }
    
    // 初始化选中第一个学生
    currentIndex.value = 0;
    currentItem.value = studentList.value[0];
    
    // 获取当前学生的试卷列表
    currentPaperList.value = currentItem.value.scanPictureVOS || [];
    currentPaperNumber.value = objectPageNumber.value; // 当前图片的页码
    
    // 查找对应页码的图片URL，添加多层安全检查
    const foundItem = currentPaperList.value.find(
        (item: any) => item.pageNo == currentPaperNumber.value
    );
    
    if (foundItem && foundItem.recognizeUrl) {
        // 找到指定页码的图片
        currentImageUrl.value = foundItem.recognizeUrl;
    } else if (currentPaperList.value.length > 0 && currentPaperList.value[0].recognizeUrl) {
        // 如果没找到指定页码，使用第一张图片作为备选
        currentImageUrl.value = currentPaperList.value[0].recognizeUrl;
    } else {
        // 如果都没有找到，设置为空字符串
        currentImageUrl.value = '';
    }
    
    // 深拷贝客观题列表，避免直接修改原始数据
    currentQuestionList.value = JSON.parse(
        JSON.stringify(currentItem.value.objectiveQuestionVOS || [])
    );
    
    // 调用客观题数据处理方法
    ObjectDataChange();
    
    // DOM更新后设置表格高度
    nextTick(() => {
        SetObjectTableHeight();
    });
}

/**
 * 设置客观题复查识别表格弹窗高度
 * @description 根据窗口高度和客观题表格区域的实际高度，动态计算主观题表格和客观题表格的高度
 */
const SetObjectTableHeight = () => {
    // 获取窗口可视区域高度（兼容多种浏览器）
    const windowViewHeight = window.innerHeight 
        || document.documentElement.clientHeight 
        || document.body.clientHeight;
    
    // 获取客观题表格区域的 DOM 元素及其位置信息
    const objectRect = objectQuestionTables.value?.getBoundingClientRect() || null;
    
    // 计算主观题复查表格高度
    // 公式：窗口高度 - 顶部间距80 - 间距20 - 搜索栏76 - 间距20 - 间距20
    subjectReviewTableHeight.value = windowViewHeight - 80 - 20 - 76 - 20 - 20;
    
    if (objectRect) {
        // 如果获取到客观题表格区域的实际高度
        console.log("客观题表格的实际高度:", objectRect.height);
        
        // 计算客观题异常处理表格高度
        // 公式：窗口高度 - 顶部间距80 - 间距20 - 间距20 - 客观题表格高度 - 标题栏76 - 间距20 - 按钮区60
        objectTableHeights.value = windowViewHeight 
            - 80   // 顶部间距
            - 20   // 间距
            - 20   // 间距
            - objectRect.height  // 客观题表格区域高度
            - 76   // 标题栏高度
            - 20   // 间距
            - 60;  // 按钮区高度
    } else {
        // 如果未获取到客观题表格区域，使用默认高度288px
        // 公式：窗口高度 - 顶部间距80 - 间距20 - 间距20 - 默认表格高度288 - 间距20 - 标题栏56 - 间距20 - 按钮区60
        objectTableHeights.value = windowViewHeight 
            - 80   // 顶部间距
            - 20   // 间距
            - 20   // 间距
            - 288  // 默认表格高度
            - 20   // 间距
            - 56   // 标题栏高度
            - 20   // 间距
            - 60;  // 按钮区高度
    }
    
    // 如果是手阅卡类型，增加56px高度
    if (markType.value == 1) {
        objectTableHeights.value += 56;
    }
    
    console.log("最终客观题表格高度:", objectTableHeights.value);
}
      

//切换显示
const ChangeUploadShow=(show:number)=>{
    showUploadReview.value=show;
    currentIndex.value=0;
    GetExamStudentList();      
}

//切换考试类型
const ChangeRoomType=(type:number)=>{
    activeName.value=type
    GetExamStudentList();
}

//切换查看类型
const ChangeReviewType=(type:number)=>{
    showReviewType.value=type
}

//切换分页
const ChangePage=(pageNum:number)=>{
    pageInfo.value.pageNum=pageNum;
}


//设置每页显示数量
const ChangePageSize=(size:number)=>{
    pageInfo.value.pageSize=size;
}
//序号自定义方法
const HandleIndexMethod=(index:number)=>{
    if(activeName.value==1){
        return index+1
    }else{
        return index+1
    }
}

//获取学生列表
const GetExamStudentList=async()=>{
    isLoading.value=true
    const params={
        examSubjectId:examSubjectId.value,//考试id
        type:activeName.value,//// 1-按考场 2-按班级
        scannedStatus:props.scanState,// 状态
        review:showUploadReview.value,// 0-否, 1-是
        schoolId:schoolId.value,
    };
    let res=await getExamStudentList(params)
    console.log("打印获取的扫描学生结果",res)
    isLoading.value=false
    if(res.code==200)
    {
       let childrenData:any[]=[];
       let allDatalist:any[]=[];   //全部学生列表
       let examInfoCount={
            unScanned:res.data.unScanned,
            examMissNum:res.data.examMissNum,
            scannedNum:res.data.scannedNum,
            abnormalNum:res.data.abnormalNum,
            examTotal:res.data.totalNum,
        };
        examStore.setExamInfoCount(examInfoCount);//设置扫描数据信息
       if(res.data.examRoomTypeTblVOS?.length>0)
        {
            res.data.examRoomTypeTblVOS.forEach((item:any)=> {
                let obj={
                    id:'index_'+item.examRoomCode, //考场id    
                    label:item.examRoomName+'('+item.totalStudentNum+'人)', //考场名称
                    studentList:item.scannedStudentTblVOS || [],//学生列表

                };
                allDatalist.push(...item.scannedStudentTblVOS);
                childrenData.push(obj);
            });
            reviewObjectClassList.value=res.data.examRoomTypeTblVOS || [];
        }
        let oneTreeData={
            id:'all',
            label:'全部'+'('+allDatalist.length+'人)',
            children:childrenData,
            studentList:allDatalist,
        };
        treeData.value=[oneTreeData];
        if(selectNodeId.value=='all')
        {
            studentList.value=allDatalist;
            pageInfo.value.total=allDatalist.length;
        }
        else
        {

        }

        // 如果是已上传状态且处于复查识别模式
        if (props.scanState === 1 && showUploadReview.value === 1) {
            console.log("复查识别的学生列表:", studentList.value);
            
            if (currentIndex.value === -1) {
                currentIndex.value = 0;
            }
            
            // 初始化当前选中的学生
            currentItem.value = studentList.value[currentIndex.value];
            currentPaperList.value = currentItem.value.scanPictureVOS || [];
            currentPaperNumber.value = objectPageNumber.value; // 当前图片的页码
            
            // 查找对应页码的图片URL
            const targetPage = currentPaperList.value.find(
                (page: any) => page.pageNo === currentPaperNumber.value
            );
            currentImageUrl.value = targetPage ? targetPage.recognizeUrl : '';
            console.log("打印当前的学生",currentItem.value);
            // 深拷贝客观题列表，避免直接修改原始数据
            currentQuestionList.value = JSON.parse(
                JSON.stringify(currentItem.value.objectiveQuestionVOS || [])
            );
            console.log('打印当前的客观题题目列表currentQuestionList', currentQuestionList.value);
            // 调用客观题数据处理方法
            ObjectDataChange();
        }
        
        // DOM 更新后设置表格高度
        nextTick(() => {
            SetObjectTableHeight();
        });
        console.log("打印获取的树形结构数据",treeData.value)

    }
}

/**
 * 获取未扫描、缺考、已上传等通用数据查询
 * @description 根据考试科目、状态等条件获取学生扫描列表数据，并构建树形结构
 */
const GetExamScanList = async () => {
    // 构建请求参数
    const params = {
        examSubjectId: examSubjectId.value,  // 考试ID
        schoolId: schoolId.value,            // 学校ID
        scannedStatus: props.scanState,      // 状态
        type: activeName.value,              // 1-按考场 2-按班级
        review: showUploadReview.value       // 0-否, 1-是
    };
    
    isLoading.value = true; // 设置加载状态
    console.log("请求参数:", params);
    
    try {
        const res = await getExamStudentList(params);
        console.log("扫描学生列表返回数据:", res);
        isLoading.value = false;
        
        if (res.code === 200) {
            // 更新头部统计信息
            let examInfoCount={
                unScanned:res.data.unScanned,
                examMissNum:res.data.examMissNum,
                scannedNum:res.data.scannedNum,
                abnormalNum:res.data.abnormalNum,
                examTotal:res.data.totalNum,
            };
            examStore.setExamInfoCount(examInfoCount);//设置扫描数据信息
            
            
            // 构建树形结构数据
            const childrenData: any[] = [];
            const allStudentList: any[] = []; // 全部学生列表
            
            if (res.data.examRoomTypeTblVOS?.length > 0) {
                res.data.examRoomTypeTblVOS.forEach((item: any) => {
                    const obj = {
                        id: 'index_' + item.examRoomCode,           // 考场ID
                        label: item.examRoomName + '(' + item.totalStudentNum + '人)', // 考场名称
                        studentList: item.scannedStudentTblVOS || [] // 学生列表
                    };
                    allStudentList.push(...item.scannedStudentTblVOS);
                    childrenData.push(obj);
                });
                reviewObjectClassList.value = res.data.examRoomTypeTblVOS || [];
            }
            
            // 创建"全部"节点
            const oneTreeData = {
                id: 'all',
                label: '全部(' + allStudentList.length + '人)',
                children: childrenData,
                studentList: allStudentList
            };
            
            treeData.value = [oneTreeData];
            
            // 根据选中的节点ID更新学生列表
            if (selectNodeId.value === 'all') {
                studentList.value = allStudentList;
            } else {
                // 查找当前选择的节点
                const foundItem = childrenData.find((item: any) => item.id === selectNodeId.value);
                console.log("当前选择节点的子节点:", foundItem);
                
                if (foundItem) {
                    studentList.value = foundItem.studentList;
                } else {
                    // 如果找不到，使用第一个节点的数据
                    studentList.value = childrenData[0] ? childrenData[0].studentList : [];
                    selectNodeId.value = childrenData[0] ? childrenData[0].id : '';
                }
            }
            
            // 如果是缺考状态，需要处理列表数据（生成填涂标记缩略图）
            if (props.scanState === 2) {
                // 找到第一个有图片数据的学生
                const imageItem = studentList.value.find((item: any) => item.scanPictureVOS?.length > 0);
                console.log("找到有缺考图片数据的学生:", imageItem);
                
                let scaledX, scaledY, scaledW, scaledH;
                scaledX = missPosition.value.x;
                scaledY = missPosition.value.y;
                scaledW = missPosition.value.w;
                scaledH = missPosition.value.h;
                
                if (imageItem) {
                    const imageUrl = imageItem.scanPictureVOS[0].recognizeUrl;
                    const imageInfo = await GetImageInfo(imageUrl); // 获取试卷图片尺寸
                    console.log("图片信息:", imageInfo);
                    
                    if (usedCardType.value === 1) {
                        // 系统卡处理
                        let templateInfo;
                        
                        if (imageInfo.width > imageInfo.height) {
                            // A3 纸张 1588*1123
                            templateInfo = {
                                width: 1588 - 30 * 2,
                                height: 1123 - 25 * 2
                            };
                        } else {
                            // A4 纸张 794*1123
                            templateInfo = {
                                width: 794 - 30 * 2,
                                height: 1123 - 25 * 2
                            };
                        }
                        
                        // 计算缩放比例
                        const x = missPosition.value.x - 30;
                        const y = missPosition.value.y - 25;
                        const w = 17;
                        const h = 10;
                        
                        // 缩放后的坐标和尺寸
                        scaledX = (x / templateInfo.width) * imageInfo.width;
                        scaledY = (y / templateInfo.height) * imageInfo.height;
                        scaledW = (w / templateInfo.width) * imageInfo.width;
                        scaledH = (h / templateInfo.height) * imageInfo.height;
                    }
                    
                    // 为每个学生生成填涂标记缩略图
                    studentList.value.forEach((item: any) => {
                        if (item.scanPictureVOS && item.scanPictureVOS.length > 0) {
                            const url = item.scanPictureVOS[0].recognizeUrl;
                            const picUrl = GetPicUrl(url, scaledX, scaledY, scaledW, scaledH);
                            item.paperUrl = picUrl; // 直接赋值，Vue 3 自动响应式
                        } else {
                            item.paperUrl = '';
                        }
                    });
                    
                    console.log("缺考学生列表处理完成:", studentList.value);
                }
            }
            
            // 更新分页总数
            pageInfo.value.total = studentList.value.length;
            console.log("选中的节点ID:", selectNodeId.value);
            
            // DOM 更新后设置树形组件的当前选中项
            nextTick(() => {
                if (classTree.value) {
                    classTree.value.setCurrentKey(selectNodeId.value);
                }
                defaultExKey.value = ['all'];
            });
            
            // 改变 key 值强制重新渲染表格
            tableKey.value = tableKey.value + 1;
            
            // 如果是已上传状态且处于复查识别模式
            if (props.scanState === 1 && showUploadReview.value === 1) {
                console.log("复查识别的学生列表:", studentList.value);
                
                if (currentIndex.value === -1) {
                    currentIndex.value = 0;
                }
                
                // 初始化当前选中的学生
                currentItem.value = studentList.value[currentIndex.value];
                currentPaperList.value = currentItem.value.scanPictureVOS || [];
                currentPaperNumber.value = objectPageNumber.value; // 当前图片的页码
                
                // 查找对应页码的图片URL
                const targetPage = currentPaperList.value.find(
                    (page: any) => page.pageNo === currentPaperNumber.value
                );
                currentImageUrl.value = targetPage ? targetPage.recognizeUrl : '';
                
                // 深拷贝客观题列表，避免直接修改原始数据
                currentQuestionList.value = JSON.parse(
                    JSON.stringify(currentItem.value.objectiveQuestionVOS || [])
                );
                
                // 调用客观题数据处理方法
                ObjectDataChange();
            }
            
            // DOM 更新后设置表格高度
            nextTick(() => {
                SetObjectTableHeight();
            });
            
        } else {
            // 请求失败，清空数据
            treeData.value = [];
            studentList.value = [];
            ElMessage.error(res.msg || '获取数据失败');
        }
    } catch (error) {
        console.error("获取扫描列表错误:", error);
        isLoading.value = false;
        ElMessage.error('网络请求失败');
    }
}

//计算高度的函数
const CalculateTableHeight = () => {
  // nextTick 确保 DOM 更新后再获取尺寸
  nextTick(() => {
    // window.innerHeight 是浏览器可视区域高度

    // 简单算法：视窗高度 - 固定占用高度
    let computedHeight = window.innerHeight - 270;
    
    // 限制最小高度，防止太矮
    if(computedHeight < 200) 
    {
      computedHeight = 200;
    }

    tableHeight.value = computedHeight;
  });
}; 


onMounted(() => {
  
    if (!examStore.currentExam) {
        console.warn('当前没有选中的考试信息')
        // 可选：如果没有数据，可以重定向回列表页或提示用户
    }
    CalculateTableHeight()//计算表格高度
    GetExamStudentList();//获取学生列表
    GetTemplateDetail();//获取模板数据
    // 监听窗口大小变化
    window.addEventListener('resize', CalculateTableHeight);
})
// 卸载时移除监听，防止内存泄漏
onUnmounted(() => {
  window.removeEventListener('resize', CalculateTableHeight);
});

</script>
 
<style lang="scss" scoped>
.content_main
{
    height: 100% !important;
}

.clear_value
{
    color:#2e64fa;
    font-size: 14px;
    cursor: pointer;
    font-weight: 500;
    margin-left: 10px;
}
</style>