<template>
 <!-- 异常处理   -->
  <div class="content_main">
    <div class="abnormal_left">
        <div class="left_nav">
            <div class="nav_list">
                <!-- abnormalType:2,//页面异常类型   2-定位异常 3-考号异常 4-客观题异常 5-选做题异常 6-空白卷异常  7 缺页异常 -->
                <div class="nav_item" :class="abnormalType==2?'item_active':''" @click="AbnormalChanage(2)">
                    <div class="nav_number" v-if="abnormalObj.locationErrorNum>0">{{ abnormalObj.locationErrorNum }}</div>
                    定位异常
                </div>
                <div class="nav_item" :class="abnormalType==3?'item_active':''" @click="AbnormalChanage(3)">
                    <div class="nav_number"  v-if="abnormalObj.examNumberErrorNum>0">{{ abnormalObj.examNumberErrorNum }}</div>
                    考号异常
                </div>
                <!-- <div class="nav_item" :class="abnormalType==7?'item_active':''" @click="AbnormalChanage(7)">
                    <div class="nav_number"  v-if="abnormalObj.losePageErrorNum>0">{{ abnormalObj.losePageErrorNum }}</div>
                    缺页异常
                </div> -->
                <div class="nav_item" :class="abnormalType==4?'item_active':''" @click="AbnormalChanage(4)">
                    <div class="nav_number"  v-if="abnormalObj.objectErrorNum>0">{{ abnormalObj.objectErrorNum }}</div>
                    客观题异常
                </div>
                <!-- <div class="nav_item" :class="abnormalType==5?'item_active':''" @click="AbnormalChanage(5)">
                    <div class="nav_number"  v-if="abnormalObj.choiceErrorNum>0">{{ abnormalObj.choiceErrorNum }}</div>
                    选做题异常
                </div>
                <div class="nav_item" :class="abnormalType==6?'item_active':''" @click="AbnormalChanage(6)" v-if="markType==1">
                    <div class="nav_number"  v-if="abnormalObj.subjectiveErrorNum>0">{{ abnormalObj.subjectiveErrorNum }}</div>
                    划分异常
                </div> -->
            </div>
            <div class="nav_button el_button">
                <!-- <div :class="isShowDraw?'is_draw_data':'is_draw_active'" @click="ShowDrawData()" v-if="abnormalType==4">显示画框</div> -->
                <el-select  v-if="abnormalType==6" style="width: 100px;" v-model="isShowDrawType" placeholder="显示类型" @change="SubjectDataChange()">
                    <el-option label="答题卡" value="1"></el-option>
                    <el-option label="划分区" value="2"></el-option>
                </el-select>
                <el-button class="refresh_btn" @click="RefreshAbnormalList()"><i class="iconfont icon_shuaxin"></i>刷新</el-button>
                <el-button class="fit_screen_btn" @click="FitScreen()">适应屏幕</el-button>
            </div>
        </div>
        <div class="left_image" :class="abnormalType==6 && isShowDrawType==2?'left_image_height_2':'left_image_height_1'">
            <!-- 定位异常试卷区 -->
            <div class="page_jg_10"></div>
            <div v-if="abnormalType==2" class="position_abnormal_content">
                <div class="template_content">
                    <div class="content_header">
                        <div class="header_left">
                            标准模板
                        </div>
                        <div class="header_right">
                            <div :class="item.pageNum==currentTemplatePageIndex?'page_num_active':'page_num_item'"  v-for="(item,index) in currentTemplateList" :key="'template_'+index" @click="ChangeTemplatePage(item)">{{item.pageNum}}</div>
                        </div>
                    </div>
                    <div class="content_canvas">
                        <PositionCanvas  :usedCardType="usedCardType" :positionList="sourcePoints"  :paperImgUrl="currentTemplateUrl" @GetCutPosition="GetCutTemaplatePosition" paperType="'template'"   v-if="currentTemplateUrl"> </PositionCanvas>
                    </div>
                </div>
                <div class="paper_content">
                    <div class="content_header">
                        <div class="header_left">
                            答题卡
                            <span v-if="currentImagePageNo==''" style="color:red;">(当前图片页码未保存)</span>
                            <span v-else style="color:green;">(当前图片页码已设置为:{{currentImagePageNo}})</span>
                        </div>
                        <div class="header_right el_button">
                            <i class="iconfont icon_nishizhen" @click="AnticlockwiseImage()"></i>
                            <i class="iconfont icon_shunshizhen" @click="ClockwiseImage()"></i>
                            <el-button type="primary" class="right_button_editor" @click="MarkBlankPage()">标记为空白页</el-button>
                            <el-button type="primary" class="right_button_editor" style="margin-left: 0px;" @click="SavePositionImage()">保存</el-button>
                        </div>
                    </div>
                    <div class="content_canvas">
                        <PositionCanvas  :usedCardType="usedCardType" :positionList="targetPoints"  :paperImgUrl="currentPaperUrl"  @GetCutPosition="GetCutStudentPosition" paperType="student" v-if="currentPaperUrl"> </PositionCanvas>
                    </div>
                </div>

            </div>
            <!-- 考号异常试卷区 -->
            <!-- abnormalType:2,//页面异常类型   2-定位异常 3-考号异常 4-客观题异常 5-选做题异常 6-空白卷异常  7 缺页异常 -->
            <!-- <div v-if="abnormalType==3  || abnormalType ==6 || abnormalType ==7" class="img_canvas_center">
                <ImageCavasShow :paperImgUrl="currentPaperUrl"></ImageCavasShow>
            </div> -->
            <!-- <div v-if="abnormalType ==4 " class="img_canvas_center">
                <ImageCanvas :currentPaperInfo="currentPaperInfo" > </ImageCanvas>
            </div> -->
            <div v-if="abnormalType==3 || abnormalType ==7 || abnormalType ==4 || abnormalType ==5" class="img_canvas_center">
                <ActionImage ref="ActionCanvas" :isDrag="true" :paperInfo="currentPageInfo"  :paperImgUrl="currentPaperUrl" :drawData="currentDrawData" :isAbnormal="true"></ActionImage>
            </div>

        </div>
        <div class="page_jg"></div>
        <div class="left_bottom" v-if="!(abnormalType==6 && isShowDrawType==2)">
            <div class="bottom_draggable draggable_width_100" >
                <div v-for="(item,index) in currentPaperList" class="bottom_img_item"  :class="currentPaperIndex == index?'img_item_cur':''" @click="ChanageCurrentPaperUrl(index, item)" :key="'paper_'+index">
                    <img style="width: 100%;height: 100%" :src="item.recognizeUrl" alt="" >
                    <div class="bottom_img_item_number" v-if="abnormalType==2">{{index+1}}</div>
                    <div class="bottom_img_item_number" v-else>
                        <span v-if="item.pageNo>0">{{item.pageNo}}</span>
                        <span v-else></span>
                    </div>
                </div>  
            </div>
        </div>
    </div>
    <div class="abnormal_right">
        <!-- 定位异常区域 -->
        <div class="right_center" v-show="abnormalType==2">
            <div class="page_jg_20" ></div>
            <div class="right_table">   
                <el-table @row-click="PendingListRowClick" :row-class-name="TableRowClassName"  border  :data="positionData.pendingList" style="width:100%;"   :height="tableHeightRight" align="left" >
                    <el-table-column align="center" width="40" type="index" label="序号"></el-table-column>  
                    <!-- <el-table-column align="center" prop="batchNo" width="45" label="批次"></el-table-column> -->
                    <el-table-column align="center"  width="65" label="批次">
                        <template v-slot="scope">
                        {{GetPositionSelNumber(scope.row)}}
                        
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="studentName" label="姓名">
                        <template v-slot="scope">
                            <span v-if="scope.row.studentName">{{scope.row.studentName}} </span>
                            <span v-else>-</span>
                        </template>
                    </el-table-column>  
                    <el-table-column align="center" prop="cardNumber" label="考号">
                        <template v-slot="scope">
                            <span v-if="scope.row.cardNumber">{{scope.row.cardNumber}} </span>
                            <span v-else>-</span>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column align="center" prop="examDate" label="班级"></el-table-column> -->
                </el-table>
                
            </div>
            <div class="right_bottom_button el_button">
                <div class="page_jg_20"></div>
                <div class="bottom_button_two">
                    <el-button @click="ReCutPaper()" class="re_cut_btn" :loading="reCutLoading">
                        {{reCutText}}
                    </el-button>
                    <el-button @click="DeleteCurrentPaper()" class="delete_paper_btn">删除当前试卷</el-button>
                </div>
                <!-- <div class="bottom_button_item">
                    <el-button @click="recyleMethod" class="recycle_bin_btn">回收站</el-button>
                </div> -->
            </div>
        </div>
        <!-- 考号异常区域 -->
        <div class="right_center" v-show="abnormalType==3">
            
            <div class="right_table">   
                <div class="right_title">
                    考号异常处理
                </div>

                <!-- abnormalType 0-正常 1-考号未识别出来 2-无此考生 3-考号重复(1,2,3都代表考号异常) 4-定位异常 5-缺页异常  -->
                <el-table ref="numberPendingTable" @row-click="PendingListRowClick" :row-class-name="TableRowClassName" :data="numberData.pendingList" max-height="300" border  stripe>
                    <el-table-column align="center" type="index" width="40" label="序号">
                    </el-table-column>
                    <el-table-column align="center"  width="65" label="批次">
                        <template v-slot="scope">
                        {{GetPositionSelNumber(scope.row)}}

                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="studentName"  width="80" label="姓名">
                        <template v-slot="scope">
                            <div v-if="scope.row.studentName" class="table_row_value">
                            <span class="card_number_repeat" v-if="scope.row.abnormalType==3">重</span> {{scope.row.studentName}} 
                            </div>
                            <span v-else>-</span>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="cardNumber" label="考号">
                        <template v-slot="scope">
                            <span v-if="scope.row.cardNumber" :class="scope.row.abnormalType==2?'card_number_error':''">{{scope.row.cardNumber}} </span>
                            <span v-else>-</span>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column align="center" prop="schoolClassName"  label="班级"></el-table-column> -->
                </el-table>
                <!-- <el-table   :data="numberData.processedList"  border max-height="150"  v-if="rightTab=='processed'">
                    <el-table-column align="center" type="index" width="60" label="序号">
                    </el-table-column>
                    <el-table-column align="center"  prop="studentName"  label="姓名"></el-table-column>
                    <el-table-column align="center" prop="exCode"  label="考号"></el-table-column>
                    <el-table-column align="center" prop="schoolClassName"  label="班级"></el-table-column>
                </el-table> -->
                <div class="right_title">
                    查询学生进行认领
                </div>
                <div  class="right_search el_button">
                    <el-input type="text" style="width: 220px;" @keyup.enter.native="GetSearchStudent" v-model="searchContent" @input="GetSearchStudent" placeholder="学生姓名、考号" >
                        <el-button slot="append" icon="el-icon-search" style="width:68px;"  @click="GetSearchStudent"></el-button>
                    </el-input>
                    <el-button  class="editor_item" @click="OpenAddStudentDialog" >新增考生</el-button>
                </div>
                <el-table  :data="searchStudetList" border :height="numberTableHeight" stripe style="width: 100%;">
                <el-table-column align="center"  prop="studentName" width="70"  label="姓名">
                        <template v-slot="scope">
                            <div class="table_row_value" :title="scope.row.studentName">
                                {{scope.row.studentName}}
                            </div>
                        </template>
                </el-table-column>
                <el-table-column align="center" prop="cardNumber"  label="考号" show-overflow-tooltip></el-table-column>
                <el-table-column align="center" prop="pageNum"  label="页数" width="70" >
                        <template v-slot="scope">
                            <div class="table_row_value" >
                                {{ GetPaperPageNum(scope.row) }}
                            </div>
                        </template>
                </el-table-column>
                <el-table-column align="center"  width="90"   label="操作">
                        <template v-slot="scope">
                            <div class="row_scan_status">
                                <div class="claim_scan_btn" v-if="scope.row.scanPictureVOS" @click="OpenViewPaper(scope.row)" >
                                    查看
                                </div>
                                <div class="disable_view_btn" v-else>
                                    查看
                                </div>
                                <div class="claim_scan_btn"  @click="KaohaoClaimConfirm(scope)">
                                    认领
                                </div>
                            </div>
                        </template>
                </el-table-column>
            </el-table>
                
            </div>
            <div class="right_bottom_button el_button">
                <div class="page_jg_20"></div>
                <div class="bottom_button_two">
                    <!-- <el-button  class="re_cut_btn" @click="OpenAddStudentDialog" >新增考生</el-button> -->
                    <el-button @click="MarkPositionAbnormal" class="abnormal_other_btn">标记定位异常</el-button>
                    <el-button @click="DeleteCurrentPaper()" class="delete_paper_btn">删除当前试卷</el-button>
                </div>
                
            </div>
        </div>

        <!-- 客观题异常区域 -->
        <div class="right_center" v-show="abnormalType==4">
            <!-- 已处理未开发完成 暂时先屏蔽切换 -->
            <div class="right_user_tab">
                <div class="tab_system_user" :class="rightTab == 'pending'?'select_cur':''" @click="ChangeTab('pending')">
                    待处理({{objectData.pendingList.length}})
                </div>
                <div class="tab_temporay_user" :class="rightTab == 'processed'?'select_cur':''" @click="ChangeTab('processed')">
                    已处理({{objectData.processedList.length}})
                </div>
            </div>
            <div class="page_jg_20"></div>
            <div class="right_table" ref="objectQuestionTable">   
                <el-table @row-click="PendingListRowClick" :row-class-name="TableRowClassName" :data="objectData.pendingList" max-height="238" border v-show="rightTab=='pending'">
                    <el-table-column align="center" type="index" label="序号" width="40"></el-table-column>  
                    <el-table-column align="center"  width="55" label="批次">
                        <template v-slot="scope">
                            {{GetPositionSelNumber(scope.row)}}
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="studentName" width="70"  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" prop="adminClassName" width="65" label="班级"></el-table-column>
                </el-table>
                <el-table @row-click="PendingListRowClick" :row-class-name="TableRowClassName"  :data="objectData.processedList"  border max-height="238"  v-show="rightTab=='processed'">
                    <el-table-column align="center" type="index" width="40" label="序号">
                    </el-table-column>
                    <el-table-column align="center"  width="55" label="批次">
                        <template v-slot="scope">
                        {{GetPositionSelNumber(scope.row)}}
                        </template>
                    </el-table-column>
                    <el-table-column align="center"  prop="studentName" width="70"  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" prop="adminClassName" width="65"  label="班级" show-overflow-tooltip></el-table-column>
                </el-table>
                <div class="right_title">
                    <div >客观题异常处理  
                        <span @click="ClearValue()"  class="clear_value">清空</span>
                    </div>
                    
                    <div ><el-checkbox v-model="isShowAbnormalQuestion" >只显示异常题</el-checkbox></div>
                </div>
            </div>
            <div class="answer_table">
                <el-table :data="questionTableData" :height="objectTableHeight" 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>
        
            <!-- <answerPaper :questionList="currentQuestionList" @selectClick="selectClick"></answerPaper> -->
        
            <div class="right_bottom_button el_button">
                <div class="bottom_button_two">
                    <el-button @click="MarkPositionAbnormal" class="abnormal_other_btn">标记定位异常</el-button>
                    <el-button @click="ObjectiveCheck" class="re_cut_btn" :loading="correctionLoading">校正完成</el-button>
                </div>
            </div>
        </div>


    </div>
  </div>
</template>
<script lang="ts" setup>
import { useExamStore } from '@/store/exam'
import { useRouter } from 'vue-router'
import { onMounted,onUnmounted, ref, computed, nextTick, watch } from 'vue';
import { ElMessage,ElMessageBox } from 'element-plus'

// 引入可能需要的 API (请根据实际路径调整)
import { getExamAbnormalList,getSearchScanStudents,claimAnswerCard, correctObjectiveQuestion,markPositionAbnormal, deletePaper ,reRecognizePosition,getTemplateDetail} from '@/api/exam'

// 引入子组件 (确保路径正确)
import PositionCanvas from '@/components/PositionCanvas.vue' // 假设路径
import ActionImage from '@/components/ActionImage.vue'// 画布图片组件
// import MarkScore from './components/MarkScore.vue'           // 假设路径

// 实例化 Store
const examStore = useExamStore()
const router = useRouter()

// ==================== 考试通用数据（可追加）====================
// 考试科目 ID
const examSubjectId = computed(() => {
  return examStore.currentExam?.id
})//计算属性

const paperSchema=computed(() => {
    return 1;
})//1-单面 2-双面

const schoolId = computed(() => {
  return 0;
})//学校id

//考试科目code
const examSubjectCode=computed(() => {
    return examStore.currentExam?.examSubjectCode
})

////客观题异常校正表格数据
const questionTableData=computed(() => {
    // 使用可选链操作符和空值合并操作符提供默认值
    const tableData = currentQuestionList.value || [];
    
    if (isShowAbnormalQuestion.value) {
        // 显示异常题
        return tableData.filter(item => item?.hasAbnormal === 1);
    }
    
    return tableData;
})



// ==================== 状态定义 ====================

// 异常类型: 2-定位异常 3-考号异常 4-客观题异常 5-选做题异常 6-划分异常(空白卷) 7-缺页异常
const abnormalType = ref(2)
const markType = ref(0) // 0-网阅卡 1-手阅卡

// 异常统计数据
const abnormalObj = ref({
    locationErrorNum: 0,   // 定位异常数
    examNumberErrorNum: 0, // 考号异常数
    losePageErrorNum: 0,   // 缺页异常数
    objectErrorNum: 0,     // 客观题异常数
    choiceErrorNum: 0,     // 选做题异常数
    subjectiveErrorNum: 0  // 划分异常数
})

// 左侧导航/显示控制
const isShowDraw = ref(false)      // 客观题是否显示画框
const isShowDrawType = ref(1)    // 划分异常显示类型: 1-答题卡 2-划分区
const isShowAbnormalQuestion = ref(false) // 是否只显示异常题

// 图片与Canvas相关 试卷图片相关数据
const currentIndex= ref(0);//当前表格学生索引
const currentItem= ref<any>({});//当前表格学生数据
const currentTemplateUrl = ref('')//试卷图片模板地址
const currentPaperUrl = ref('')//试卷图片地址
const currentImagePageNo = ref('')//当前图片页码
const currentPaperIndex = ref(0)//当前图片索引
const currentTemplatePageIndex = ref(1)////当前模板页索引
const currentDrawData= ref<any[]>([]);//画框数据
const currentPaperList = ref<any[]>([]) // 底部缩略图列表
const currentPageInfo = ref<any>({})    // 当前页面信息




// 定位异常相关
const usedCardType = ref(2) // 1 系统卡  2 三方卡  默认2
const sourcePoints = ref<any[]>([]) // 模板点位
const targetPoints = ref<any[]>([]) // 学生点位
const currentTemplateList = ref<any[]>([]) // 模板数据

//客观题异常相关
const currentQuestionList= ref<any[]>([]);//客观题题目异常校正列表

// 右侧表格数据
const positionData = ref({ pendingList: [] }) // 定位异常待处理
const numberData = ref({ pendingList: [], processedList: [] }) // 考号异常
const losePageData = ref({ pendingList: [] }) // 缺页异常
const objectData = ref({ pendingList: [], processedList: [] }) // 客观题异常
const choiceData = ref({ pendingList: [], processedList: [], choiceQuestion: [] }) // 选做题异常
const subjectiveData = ref({ pendingList: [], processedList: [] }) // 划分异常

// 搜索与查询
const searchContent = ref('')//卡号异常搜索关键词
const searchStudetList = ref<any[]>([])//考号异常搜索结果列表
// 用于取消请求的控制器
let searchAbortController: AbortController | null = null;
const searchTimer=ref<number | null>(null);//搜索请求定时器;//搜索请求定时器
const searchTimestamp=0;//search请求时间戳

// 表格高度与Key
const tableHeightRight = ref(200)//定位表格高度
const numberTableHeight = ref(200);//考号异常表格高度

const objectTableHeight = ref(200);//客观题异常处理表格高度
const subjectiveTableHeight = ref(200)
const tableKey = ref(0)

const rotationAngle=ref(0);//旋转角度

// 其他状态
const rightTab = ref('pending') // pending | processed
const reCutLoading = ref(false)
const reCutText = ref('重新识别')
const correctionLoading = ref(false)
const subjectStudentIndex = ref(-1)
const subjectStudentAbnormal = ref<any[]>([])
const subjectStudentQuestion = ref<any[]>([])
const subjectiveTableData = ref<any[]>([])
const choiceHeader = ref([])

// Canvas Refs

const PaperCanvas = ref()
const ActionCanvas = ref()
const objectQuestionTable = ref<HTMLElement | null>(null);
const numberPendingTable=ref<any>(null);//考号异常待处理表格高度

// ==================== 计算属性 ====================



// ==================== 方法定义 ====================

// 1. 切换异常类型
const AbnormalChanage = (type: number) => {
    abnormalType.value = type
    // TODO: 加载对应类型的异常列表数据
    console.log('切换异常类型:', type)
    ClearCurrentData();//先清空数据
    //定位异常处理
    if(type==2)
    {
        console.log('定位异常',positionData.value)
        if(positionData.value.pendingList.length>0)
        {
            currentIndex.value=0;
            currentItem.value=positionData.value.pendingList[currentIndex.value];//当前学生数据
            currentPaperList.value=currentItem.value.scanPictureVOS || [];//试卷图片列表
            console.log('试卷图片列表',currentPaperList.value)
            currentPaperUrl.value=currentPaperList.value[0].recognizeUrl;//当前图片地址
        }
        GetTemplateDetail();//调用模板数据
    }

    //考号异常 3
    if(type==3)
    {
        console.log('考号异常',numberData.value)
        if(numberData.value.pendingList.length>0)
        {
            currentIndex.value=0;
            currentItem.value=numberData.value.pendingList[currentIndex.value];//当前学生数据
            currentPaperList.value=currentItem.value.scanPictureVOS || [];//试卷图片列表
            currentPaperUrl.value=currentPaperList.value[0].recognizeUrl;//当前图片地址
            currentImagePageNo.value=currentPaperList.value[0].pageNo;//当前图片的页码
        }
        else
        {
            ClearCurrentData();
        }
    }
    //客观题异常
    if(type==4)
    {
        console.log('客观题异常',objectData.value)
        let studentList=rightTab.value=='pending'?objectData.value.pendingList:objectData.value.processedList;
        if(studentList.length>0)
        {

            currentItem.value=studentList[currentIndex.value];//当前学生数据
            currentPaperList.value=currentItem.value.scanPictureVOS || [];//试卷图片列表
            currentPaperUrl.value=currentPaperList.value[0].recognizeUrl;//当前图片的地址
            currentImagePageNo.value=currentPaperList.value[0].pageNo;//当前图片的页码

            //客观题校正列表数据
            currentQuestionList.value=JSON.parse(JSON.stringify(currentItem.value.objectiveQuestionVOS || []));

            console.log('客观题异常',currentItem.value)
            ObjectDataChange();//客观题答案回显
        }
        else
        {
            ClearCurrentData();
        }

    }
    CalculateTableHeight();//计算表格高度
}

//当前数据数据重置
const ClearCurrentData = () => {
    currentIndex.value = 0;//重置索引
    currentItem.value={};//当前学生数据
    currentPaperList.value=[];//试卷图片列表
    currentPaperUrl.value="";//当前图片地址
    currentQuestionList.value=[];//清空客观题数据
    currentDrawData.value=[];//清空画框数据
}

// 2. 刷新异常列表
const RefreshAbnormalList = () => {
    // TODO: 调用接口刷新当前 abnormalType 的数据
    console.log('刷新列表')
    ClearCurrentData();
    GetAbnormalList();
}

// 3. 适应屏幕
const FitScreen = () => {
    // TODO: 调用 ActionImage 或 Canvas 组件的 fit 方法
    console.log('适应屏幕')
}

// 4. 显示/隐藏画框 (客观题)
const ShowDrawData = () => {
    isShowDraw.value = !isShowDraw.value
    // TODO: 更新 ActionImage 的 drawData 显示状态
    
}

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

// 6. 模板页码切换
const ChangeTemplatePage = (item: any) => {
    currentTemplatePageIndex.value = item.pageNum
    // TODO: 加载对应页码的模板图片
}

// 7. 获取切割点位 (模板)
const GetCutTemaplatePosition = (points: any[]) => {
    sourcePoints.value = points
    console.log('获取模板点位', points)
}

// 8. 获取切割点位 (学生)
const GetCutStudentPosition = (points: any[]) => {
    targetPoints.value = points
    console.log('获取学生点位', points)
}

// 9. 图片旋转
const AnticlockwiseImage = () => {
    // TODO: 逆时针旋转
    console.log('逆时针旋转')
}
const ClockwiseImage = () => {
    // TODO: 顺时针旋转
    console.log('顺时针旋转')
}

// 10. 标记为空白页
const MarkBlankPage = () => {
    // TODO: 调用接口标记当前试卷为空白页
    console.log('标记空白页')
}

// 11. 保存定位信息
const SavePositionImage = () => {
    // TODO: 提交 sourcePoints 和 targetPoints 到后端
    console.log('保存定位')

    if(currentPaperList.value.length==0)
    {
        ElMessage.error('没有定位异常哦!');
        return
    }
    
    console.log("打印当前的模板页",currentTemplateList.value);
    console.log("打印当前的模板页码",currentTemplatePageIndex.value);
    console.log("打印当前currentPaperList",currentPaperList.value);
    console.log("打印当前图片的地址",currentPaperUrl.value);
    console.log("打印当前currentPaperNumber",currentPaperIndex.value);
    console.log("打印当前的系统卡类型",usedCardType.value);
    
    let hasError = false;
    currentPaperList.value.forEach((item,index) => {
        console.log("打印当前图片的索引",item);
        if(index==currentPaperIndex.value)
        {
            
            if(usedCardType.value==1)
            {
                //系统卡 需要把两个点转成4个点
                item.sourcePoints=sourcePoints.value;//模板上的四个点的坐标
                item.targetPoints=targetPoints.value;//坐标位置 左上 右上 右下 左下
            }
            else
            {
                item.sourcePoints=sourcePoints.value;//模板上的四个点的坐标
                item.targetPoints=targetPoints.value;//学生图片上的四个点的坐标
            }
            
            if(item.targetPoints.length==0)
            {
                //定位点未设置 不可保存
                ElMessage.error('请选择定位点!');
                hasError = true;
                return; //跳出当前循环
            }
            else
            {
                
                item.pageNo=currentTemplatePageIndex.value; 
                item.rotate=rotationAngle.value;//旋转角度
                currentImagePageNo.value=item.pageNo;
                console.log("打印当前的图片页码",currentImagePageNo);
                item.isSave=true;//增加是否处理保存图片页码的标识
            }
            
        }
    });
    
    if(hasError) {
        return; //如果有错误，不执行后续的保存成功提示
    }
    
    console.log("打印保存后currentPaperList",currentPaperList.value);
    

    
    
    console.log("打印保存后currentPaperList",currentPaperList.value);
    ElMessage.success('保存成功');
}

// 12. 底部缩略图切换
const ChanageCurrentPaperUrl = (index: number, item: any) => {
    currentPaperIndex.value = index
    currentPaperUrl.value = item.recognizeUrl
    currentPageInfo.value = item
    // TODO: 加载新试卷的详细数据
}

// 13. 右侧表格行点击
const PendingListRowClick = (row: any, column: any, event: Event) => {
    // TODO: 高亮选中行，并加载该学生的试卷图片到左侧
    console.log('点击行:', row)
    if(abnormalType.value==2)
    {
        
    }
    //考号异常
    if(abnormalType.value==3)
    {
        currentItem.value=row;

        currentPaperList.value=currentItem.value.scanPictureVOS || [];//试卷图片列表
        currentPaperUrl.value=currentPaperList.value[0].recognizeUrl;//当前图片地址
        currentImagePageNo.value=currentPaperList.value[0].pageNo;//当前图片的页码
    }

    //客观题异常
    if(abnormalType.value==4)
    {
        currentItem.value=row;
        let studentList=rightTab.value=='pending'?objectData.value.pendingList:objectData.value.processedList;
        currentIndex.value=studentList.findIndex((item:any)=>item.id==currentItem.value.id);
        
        currentPaperList.value=currentItem.value.scanPictureVOS || [];//试卷图片列表
        currentPaperUrl.value=currentPaperList.value[0].recognizeUrl;//当前图片地址
        currentImagePageNo.value=currentPaperList.value[0].pageNo;//当前图片的页码
        currentQuestionList.value=JSON.parse(JSON.stringify(currentItem.value.objectiveQuestionVOS || []));
        console.log('客观题校正异常数据',currentQuestionList.value);
        console.log('客观题currentIndex',currentIndex.value);
    }
}

// 14. 表格行样式
const TableRowClassName = ({ row, rowIndex }: any) => {
    // TODO: 根据 row 的状态返回 class 字符串
    //定位异常和考号异常 都以 wholePaperId 为判断条件
    if(abnormalType.value==2 || abnormalType.value==3)
    {
        if(row.wholePaperId==currentItem.value.wholePaperId)
        {
            return 'selected_row'
        }
        else
        {
            return ''
        }
    }
    //客观题异常  以id 为判断条件
    if(abnormalType.value==4 )
    {
        if(row.id==currentItem.value.id)
        {
            return 'selected_row'
        }
        else
        {
            return ''
        }
    }
    return ''
}

// 14. 客观题表格行样式
const ObjectTableClassName=({ row, rowIndex }: any) => { 

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

}

// 15. 获取批次号显示
const GetPositionSelNumber = (row: any) => {
    // TODO: 格式化批次号
    return row.batchNo || '-'
}

// 16. 重新识别 (定位异常)
const ReCutPaper = async () => {
    
    
    if(currentPaperList.value.length==0)
    {
        ElMessage.error('没有定位异常哦!');
        return
    }

    // 先判断是否图片都做过校正对应处理
    const unsavedItems = currentPaperList.value.filter(item => !item.isSave);
    console.log("打印未保存的图片", unsavedItems);
    if (unsavedItems.length > 0) {
            // 提取未保存图片的索引信息（索引+1）
        const indices = unsavedItems.map(item => {
            const index = currentPaperList.value.indexOf(item);
            return index + 1; // 索引从0开始，显示时加1
        }).join('、');
        ElMessage.error(`请给第${indices}张图片设置对应的模板页码!`);
        return;
    }
    let pictures: Array<{
        picId: any;
        pageNo: any;
        rotate: any;
        sourcePoints: number[][];
        targetPoints: number[][];
    }> = [];
    let templatePageList=[];
    console.log("打印当前卡类型",usedCardType.value);
    console.log("打印当前的卡类型",currentPaperList.value);
    currentPaperList.value.forEach(item => {

        let sourcePoints= [];
        let targetPoints= [];
        if(item.pageNo!=-1)
        {
            sourcePoints= item.sourcePoints.map(point => [point.x, point.y]);
            targetPoints= item.targetPoints.map(point => [point.x, point.y]);
            
        }
        else
        {
            sourcePoints= [[0,0],[0,0],[0,0],[0,0]];
            targetPoints= [[0,0],[0,0],[0,0],[0,0]];
        }
        if(usedCardType.value==2)
        {
        
            //三方卡 需要把四个点转成两个点
            
        
            console.log("打印三方卡的定位坐标",sourcePoints,targetPoints);
            if(item.pageNo==-1)
            {
                //空白页
                sourcePoints=[[0,0],[0,0]];
                targetPoints=[[0,0],[0,0]];
            }
            else
            {
                console.log("打印当前三方卡的定位坐标",item.sourcePoints,item.targetPoints);
                sourcePoints=[];
                sourcePoints.push([item.sourcePoints[0].x,item.sourcePoints[0].y]);
                sourcePoints.push([item.sourcePoints[2].x,item.sourcePoints[2].y]);
                targetPoints=[];
                targetPoints.push([item.targetPoints[0].x,item.targetPoints[0].y]);
                targetPoints.push([item.targetPoints[2].x,item.targetPoints[2].y]);
            }
            

        }
        
        
        pictures.push({
            picId:item.id,//图片id
            pageNo:item.pageNo,//图标页码
            rotate:item.rotate,//旋转角度
            sourcePoints:sourcePoints,//模板上的四个点的坐标
            targetPoints:targetPoints,//学生图片上的四个点的坐标
        });
        let obj={
            pageNo:item.pageNo,
            sourcePoints:item.sourcePoints,//模板上的四个点的坐标
            targetPoints:item.targetPoints,//学生图片上的四个点的坐标
        };
        templatePageList.push(obj)
    });
    
    // 注意：templatePageList 需要在组件中定义为响应式变量
    // const templatePageList = ref<any[]>([])
    // paperSchema 也需要定义
    // const paperSchema = ref(1) // 1-单面 2-双面
    
    let param={
        examSubjectId:examSubjectId.value,
        // schema:paperSchema.value,//双面扫描 1-单面 2-双面
        pictures:pictures,//图片列表集合 图片id picId  图片页码 pageNo
    }; 
    
    reCutLoading.value=true;//重新识别loading
    reCutText.value='识别中,请稍候...';
    
    try {

        const res = await reRecognizePosition(param);
        
        reCutLoading.value=false;//重新识别loading
        reCutText.value='重新识别';
        
        if(res.code==200)
        {
            
            console.log("重新识别结果",res);
            ElMessage.success('重新识别成功!');
            currentPaperUrl.value='';
            GetAbnormalList();
        }
        else
        {
            ElMessage.error(res.msg);
        
        }
    } catch (error) {
        reCutLoading.value=false;
        reCutText.value='重新识别';
        ElMessage.error('重新识别失败');
        console.error('重新识别错误:', error);
    }
}

// 17. 删除当前试卷
const DeleteCurrentPaper = () => {
    // TODO: 二次确认后删除
    console.log('删除试卷',currentItem.value)
    ElMessageBox.confirm('确认删除该试卷吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'page_dialog',
    }).then(async () => {

        const param={
            examSubjectId:examSubjectId.value,//考试科目id
            pictureIds:currentItem.value.scanPictureVOS.map((item: { id: any }) => item.id),//图片id列表
            batchNo:currentItem.value.batchNo,//批次号
            schoolId:schoolId.value,//学校id
        };
        const res = await deletePaper(param)
        console.log('删除试卷结果:', res)
        if(res.code==200)
        {
            ElMessage.success('删除成功')
            GetAbnormalList(); 
        }
        else
        {
            ElMessage.error(res.msg);
        }
    })
}

// 18. 考号异常 - 搜索学生
const GetSearchStudent = () => {
    // TODO: 根据 searchContent 搜索学生列表
    console.log('考号搜索学生:', searchContent.value)
    //清除之前的定时器
    if(searchTimer.value)
    {
        clearTimeout(searchTimer.value);
    }

    //如果搜索的内容为空，清空结果并返回
    if (!searchContent.value.trim()) {
        searchStudetList.value = [];
        return;
    }

    // 防抖处理：300ms 后执行搜索
    searchTimer.value = setTimeout(() => {
        GetSearchScanStudentList();
    }, 300);

}

// 搜索学生列表
const GetSearchScanStudentList = async () => {
    const keyword = searchContent.value.trim();
    
    // 如果内容为空，清空列表并返回
    if (!keyword) {
        searchStudetList.value = [];
        return;
    }

    //1. 取消上一次未完成的请求
    if (searchAbortController) {
        searchAbortController.abort();
    }

    // 2. 创建新的 AbortController
    searchAbortController = new AbortController();
    const signal = searchAbortController.signal;

    const param = {
        examSubjectId: examSubjectId.value,
        chooseCode:'2',//是学号还是考号
        studentName: keyword,
        schoolId: schoolId.value,
    };

    console.log("打印通用查询学生列表的参数", param);

    try {
        // 3. 发起请求，传入 signal
        const res = await getSearchScanStudents(param, { signal });

        // 4. 处理成功响应
        if (res.code === 200) {
            searchStudetList.value = res.data || [];
           
        }
    } catch (error: any) {
        // 5. 处理错误
        if (error.name === 'CanceledError' || error.message === 'The operation was aborted.') {
            // 请求被取消，通常不需要做任何操作，静默忽略
            console.log('之前的搜索请求已取消');
        } else {
            console.error('搜索学生列表失败:', error);
            
        }
    }
};


// 19. 考号异常 - 新增考生
const OpenAddStudentDialog = () => {
    // TODO: 打开新增弹窗
    console.log('新增考生')
}

// 20. 考号异常 - 查看试卷
const OpenViewPaper = (row: any) => {
    // TODO: 预览该学生的试卷
    console.log('查看试卷:', row)
}

// 21. 考号异常 - 认领
const KaohaoClaimConfirm = (scope: any) => {
    // TODO: 确认认领逻辑
    if (!currentItem.value?.wholePaperId) {
        ElMessage.warning('请选择待处理的异常！')
        return
    }
    
    ElMessageBox.confirm('确定要认领为当前的学生吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'page_dialog',
    }).then(async () => {
        const pictureIds = currentItem.value.scanPictureVOS.map((item: any) => item.id);
        
        const param = {
            pictureIds: pictureIds,
            studentScanId: scope.row.id,
        }
        
        try {
            const res = await claimAnswerCard(param);
            console.log("打印认领返回结果", res);
            if (res.code === 200) {
                ElMessage({
                    type: 'success',
                    message: '认领成功'
                })
                searchContent.value = "";
                searchStudetList.value = [];
                console.log("打印当前选择的异常数据索引", currentIndex.value);
                console.log("打印当前的数据", currentItem.value);
                
                // TODO: 调用 GetAbnormalList 更新考号异常列表数据
                GetAbnormalList();
            } else {
                ElMessage({
                    type: 'error',
                    message: res.msg + '!'
                })
            }
        } catch (error) {
            console.error('认领失败:', error);
            ElMessage({
                type: 'error',
                message: '认领失败，请重试'
            })
        }
    }).catch(() => {
        // 用户取消操作
    });
}

// 22. 获取页数
const GetPaperPageNum = (row: any) => {
    return row.scanPictureVOS ? row.scanPictureVOS.length : '-'
}

// 23. 标记为定位异常 (从考号/缺页转定位)
const MarkPositionAbnormal = () => {
    // TODO: 调用接口修改异常类型
    console.log('标记为定位异常',currentItem.value)

    ElMessageBox.confirm('是否确定标记为定位异常？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        customClass: 'page_dialog',
    }).then(async () => {
        const pictureIds = currentItem.value.scanPictureVOS.map((item: { id: any }) => item.id);
        
        const param = {
            pictureIds: pictureIds,
            studentScanId: currentItem.value.id || '',
        }
        
        try {
            const res = await markPositionAbnormal(param);
            if (res.code === 200) {
                ElMessage({
                    type: 'success',
                    message: '已成功标记为定位异常'
                });
                GetAbnormalList();//获取异常列表
            }
            else {
                ElMessage({
                    type: 'error',
                    message: res.msg + '!'
                })
            }
        } catch (error) {
            console.error('标记定位异常失败:', error);
        }
    }).catch(() => {
        // 用户取消操作
    });
}

// 24. 标记为考号异常 (从缺页转考号)
const MarkExamNumberAbnormal = () => {
    // TODO: 调用接口修改异常类型
    console.log('标记为考号异常')
}

// 25. 缺页删除
const LosePageDelete = () => {
    // TODO: 调用 delete_batch_pic 接口
    console.log('缺页删除')
}

// 26. 切换待处理/已处理 Tab
const ChangeTab = (tab: string) => {
    rightTab.value = tab;
    AbnormalChanage(abnormalType.value);
    // TODO: 可能需要重新加载数据或过滤
    CalculateTableHeight();//计算表格高度
}

// 27. 清空选择 (客观题)
const ClearValue = () => {
    // TODO: 清空当前题目的选择
    console.log('清空')

    currentQuestionList.value.forEach(item => {
        item.selectValue = '';
    });
    const obj=currentQuestionList.value.reduce((acc,item)=>{
        acc[item.objectiveQuestionNum]=item.selectValue
        return acc
    },{});
    console.log("打印新的答案对象",obj);
    // this.objectData.jsonObj=JSON.stringify(obj);
    // this.currentItem.objectiveQuestionVOS=this.objectData.jsonObj;
    // console.log("打印新的答案字符串",this.objectData.jsonObj);
    ObjectDataChange();//客观题数据处理
}

// 28. 客观题 - 选项转换辅助
const GetLetterToNumber = (num: String) => {
    let index=Number(num);
    // A->1, B->2...
     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[index] || '';
}
//智能判分 没有判断题
const GetLetterToNumberTF = (letter: string) => {
    // T/F 处理
    return letter
}

//将答案转换成数组
const GetAnswerArray = (selectValue:any)=>{
    // 处理各种边界情况
    if (!selectValue || selectValue === '') {
        return [];
    }
    // 使用正则表达式分割，过滤掉空值
    return selectValue.split(/[,\s]+/).filter((answer: string) => answer.trim() !== '');
}


// 29. 客观题 - 判断是否存在
const IsCunzai = (selectValue: any, value: any) => {
    // TODO: 判断 selectValue 中是否包含 value
    
    let result=false;
    if(selectValue.includes(value))
    {
        result=true;
    }
    return result;
}

// 30. 客观题 - 选择答案
const ChooseAnswer = (row: any, answer: any) => {
    // TODO: 更新 row.selectValue
    console.log('选择题:', row)
    console.log('选择答案:', answer)
    let answers = GetAnswerArray(row.selectValue)
    const index = answers.indexOf(answer)
    if (index > -1) {
        // 如果已存在，则移除
        answers.splice(index, 1)
    } else {
        // 否则添加
        answers.push(answer)
    }
    // 更新回 row.selectValue，并排序（可选）
    row.selectValue = answers.sort().join(',')
    // 调用更新方法
    ObjectDataChange()
}

// 31. 客观题校正完成
const ObjectiveCheck = async () => {
    
    if(!currentItem.value?.id) {
        ElMessage.warning('请选择待处理的异常！')
        return
    }
    const params = {
        id: currentItem.value.id,
        objectiveQuestionDTOS: currentQuestionList.value
    };
    
    correctionLoading.value = true
    console.log("校正客观题参数", params)
    
    try {
        const res = await correctObjectiveQuestion(params)
        correctionLoading.value = false
        
        if (res.code === 200) {
            ElMessage({
                type: 'success',
                message: '校正成功'
            })
            
            let studentList = rightTab.value === 'pending' 
                ? objectData.value.pendingList 
                : objectData.value.processedList
            
            console.log("打印学生列表", studentList)
            console.log("打印当前学生索引", currentIndex.value)
            
            if (currentIndex.value < studentList.length - 1) {
                if(rightTab.value === 'processed') {
                    currentIndex.value = currentIndex.value + 1
                }
            } else {
                console.log("已经是最后一个学生")
                currentIndex.value = 0
            }
            console.log("打印当前索引", currentIndex.value)
            GetAbnormalList()
        } else {
            ElMessage({
                type: 'error',
                message: res.msg || '校正失败'
            })
        }
    } catch (error) {
        correctionLoading.value = false
        console.error('校正客观题失败:', error)
        ElMessage({
            type: 'error',
            message: '校正失败，请重试'
        })
    }
}

// 32. 选做题 - 选择答案
const ChoiceAnswer = (row: any, option: any) => {
    // TODO: 更新选做题选择
    console.log('选做选择:', option)
}

// 33. 选做题校正完成
const ChoiceCheck = () => {
    correctionLoading.value = true
    // TODO: 提交选做题修正结果
    setTimeout(() => {
        correctionLoading.value = false
        ElMessage.success('校正成功')
    }, 1000)
}

// 34. 划分异常 - 得分点击
const GetMarkScoreClickItem = (score: number, item: any, index: number) => {
    // TODO: 处理主观题打分
    console.log('打分:', score)
}

// 35. 划分异常 - 修改分数
const ChangeSubjectScore = () => {
    // TODO: 防抖提交分数修改
    console.log('分数变更')
}

// 36. 划分异常校正完成
const SubjectiveCheck = () => {
    correctionLoading.value = true
    // TODO: 提交主观题修正结果
    setTimeout(() => {
        correctionLoading.value = false
        ElMessage.success('校正成功')
    }, 1000)
}

//定位异常数据处理
const  PositionAbnormal= () => { 
    console.log("定位异常数据处理");

}

//初始化重置数据
const ResetData = () => { 
    // rotationAngle.value = 0;
    currentPaperIndex.value=0;
}

// ==================== API 请求 ==========

//通用获取异常列表数据
const GetAbnormalList = async () => {
    const params={
        examSubjectId: examSubjectId.value,//考试id
        schoolId:schoolId.value,
    };
    const res = await getExamAbnormalList(params);
    console.log("打印异常数据",res);
    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);//设置扫描数据信息
        //异常数据处理
        if(res.data.abnormalGroupVO)
        {
            
            //定位异常处理
            if(res.data.abnormalGroupVO.dwAbnormal)
            {
                positionData.value.pendingList = res.data.abnormalGroupVO.dwAbnormal || [];
            }

            //考号异常处理
            if(res.data.abnormalGroupVO.cardNumberAbnormal)
            {
                numberData.value.pendingList = res.data.abnormalGroupVO.cardNumberAbnormal || [];
            }

            //客观题异常处理
            if(res.data.abnormalGroupVO.objectiveAbnormal)
            {
                objectData.value.pendingList = res.data.abnormalGroupVO.objectiveAbnormal || [];
                
            }
            else
            {
                //清空数据
                objectData.value.pendingList = [];
                currentIndex.value = 0;
                currentItem.value={};//当前学生数据
                currentPaperList.value=[];//试卷图片列表
                currentPaperUrl.value="";//当前图片地址
                currentQuestionList.value=[];//清空客观题数据

            }
            if(res.data.abnormalGroupVO.dealObjectiveAbnormal)
            {
                objectData.value.processedList = res.data.abnormalGroupVO.dealObjectiveAbnormal || [];
            }
            else
            {
                objectData.value.processedList = [];
                currentIndex.value = 0;
            }

            abnormalObj.value={
                locationErrorNum: positionData.value.pendingList.length, // 定位异常数量
                examNumberErrorNum: numberData.value.pendingList.length, // 考号异常数量
                losePageErrorNum: losePageData.value.pendingList.length, // 缺页异常数量
                objectErrorNum: objectData.value.pendingList.length, // 客观题异常数量
                choiceErrorNum: choiceData.value.pendingList.length, // 选做题异常数量
                subjectiveErrorNum: subjectiveData.value.pendingList.length, // 划分异常数量
            };//异常数据
            console.log("打印异常数据",abnormalObj.value);
            console.log("打印考号异常数据",numberData);
            AbnormalChanage(abnormalType.value);
        }




    }
    else
    {

    }

}
 
//获取模板详情
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);
        currentTemplatePageIndex.value=currentTemplateList.value[0].pageNum;
        currentTemplateUrl.value=item.templateUrl;
       })
       


    }
    else
    {

    }
}

// ==================== 生命周期 ====================

onMounted(() => {
    if (!examStore.currentExam) {
        console.warn('当前没有选中的考试信息')
    } else {
        // TODO: 初始化加载异常统计数据
        // LoadAbnormalStats()
        // LoadAbnormalList(abnormalType.value)
    }
    GetAbnormalList();
    GetTemplateDetail();//获取模板数据
    // 监听窗口变化调整高度
    window.addEventListener('resize', CalculateTableHeight)
    CalculateTableHeight()

    
});
// 组件卸载时清理，防止内存泄漏
onUnmounted(() => {
    if (searchAbortController) {
        searchAbortController.abort();
    }
    //清除之前的定时器
    if(searchTimer.value)
    {
        clearTimeout(searchTimer.value);
    }
});


//计算表格高度
const CalculateTableHeight = () => {
    nextTick(() => {

        tableHeightRight.value = window.innerHeight - 220;//定位表格的高度
        if(abnormalType.value==3)
        {
            //考号异常表格高度计算
            const tableContainerEl = numberPendingTable.value?.$el || numberPendingTable.value;
            const numberRect = tableContainerEl && 
                            typeof tableContainerEl.getBoundingClientRect === 'function' ? 
                            tableContainerEl.getBoundingClientRect() : null;
            const containerHeight = numberRect ? numberRect.height : 200;
            numberTableHeight.value=window.innerHeight - containerHeight - 345;

        }
        if(abnormalType.value==4)
        {
            //客观题高度计算
            const tableContainerEl = objectQuestionTable.value
            const objectRect = tableContainerEl && 
                            typeof tableContainerEl.getBoundingClientRect === 'function' ? 
                            tableContainerEl.getBoundingClientRect() : null
            const containerHeight = objectRect ? objectRect.height : 200;
            console.log("打印表格高度",containerHeight);

            objectTableHeight.value=window.innerHeight - containerHeight - 270;
        }
       
        


    })
}

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

.clear_value
{
    margin-left: 10px;
    // text-emphasis-style: dot;        /* 实心小圆点 • */
        // text-emphasis-style: circle;     /* 空心圆圈 ○ */
        // text-emphasis-style: double-circle; /* 双圆圈 ◉ */
        // text-emphasis-style: triangle;   /* 三角形 ▲ */

        /* 自定义字符 */
        // text-emphasis-style: '★';        /* 使用星号 */
    text-emphasis-style: '※';       /* 使用参考标记 */
    text-emphasis-color: red;
    text-emphasis-position: under; /* 下方居中 */
    cursor: pointer;
}
</style>