<template>
    <el-dialog title="" v-model="showDialog" class="page_full_dialog" :modal-append-to-body="false"  append-to-body fullscreen height="100%">
        <div class="abnormal_detail">
            <div class="detail_header">
                <div class="go_back" @click="CloseDialog()">
                    <i class="iconfont icon_return"></i>返回扫描
                </div>
                <div class="scan_button_list">
                    <!-- 状态  0  未扫描  1 已上传 2  缺考  3 异常 -->
                    <div class="button_item item_no_scan"  :class="scanState==0?'item_no_scan_active':''" @click="ScanStateChange(0)">
                        未扫描（{{unScanned}}人）
                    </div>
                    <div class="button_item item_miss_exam"  :class="scanState==2?'item_miss_exam_active':''" @click="ScanStateChange(2)">
                        缺考（{{ examMissNum }}人）
                    </div>
                    <div class="button_item item_abnormal"  :class="scanState==3?'item_abnormal_active':''" @click="ScanStateChange(3)">
                        异常（{{ abnormalNum }}份）
                    </div>
                    <div class="button_item item_sucess_upload"  :class="scanState==1?'item_sucess_upload_active':''" @click="ScanStateChange(1)">
                        已上传（{{ scannedNum }}人）
                    </div>
                </div>
            </div>
            <div class="detail_content">
                <!-- 异常 -->
                <Abnormal v-if="scanState == 3"></Abnormal>
                <!-- 状态  0  未扫描  1 已上传 2  缺考  3 异常 -->
                <TableList :scanState="scanState" v-else></TableList>
            </div>
        </div>

    </el-dialog>
</template>
<script lang="ts" setup>
import { useExamStore } from '@/store/exam'
import { useUserStore } from '@/store/user'
import { useRouter } from 'vue-router'
import { onMounted ,ref,computed,onUnmounted,nextTick,watch } from 'vue';
import { hasImportStudent,getBatchList,getCurrentBatchNo,deleteBatch,updateScanCount } from '@/api/exam'
import { ElMessageBox, ElMessage } from 'element-plus'

import TableList from './abnormal/tableList.vue'
import Abnormal from './abnormal/abnormal.vue'

// 实例化 Store
const examStore = useExamStore()
const userStore = useUserStore()

const router = useRouter()

// 定义 Props 和 Emits
const props = defineProps<{
  modelValue: boolean,
  scanState: number,//扫描状态
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()
// 弹窗显示状态的双向绑定
const showDialog = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

watch(() => props.scanState, (newState) => {
    console.log("弹窗显示状态变更为",newState);
    scanState.value = newState;
});



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

//考试科目code
const examSubjectCode=computed(() => {
    return examStore.currentExam?.examSubjectCode
})
//未扫描
const unScanned=computed(() => {
    return examStore.unScanned;
})
const examMissNum=computed(() => {
    return examStore.examMissNum;
})
const abnormalNum=computed(() => {
    return examStore.abnormalNum;
})
const scannedNum=computed(() => {
    return examStore.scannedNum;
})




const selectSchoolId=ref(0);//学校ID

const params=ref({
    batchNo:'',
    keyWord:''
})

const scanClientStates=ref(false);//客户端状态
const scanClientVersion=ref('');//客户端版本
const isScanning=ref(false);//是否正在扫描 扫描状态
const hasMakeTemplate=ref(false);//模版是否制作完成
const currentBatchNo=ref('');//当前批次号
const currentBatchNoId=ref('');//当前批次号id
const loadingText=ref('');//加载文本
const baseUrl=import.meta.env.VITE_API_BASE_URL;
const uploadUrl=`https://dev3.k12100.net/teaching/api/v1/ai_exam_scan/upload_multi_img`;//图片上传地址



const tableHeight=ref(500);
const scanIdentifyList=[                
    {
        label:'考号',
        value:'2',
    },
    {
        label:'学号',
        value:'1',
    }
];//识别号列表

const isImportStudent=ref(false);//是否导入了学生名单
const showSelectStudent=ref(false);//是否显示选择学生名单弹窗

const scanState=ref(0);//扫描状态 0 未扫描 1 已上传 2 缺考 3 异常
const scanDataInfo=ref({
    abnormalNum:0,//异常数量
    examMissNum:0,//缺考数量
    unScanned:0,//未扫描数量
    scannedNum:0,//已上传数量
    examTotal:0,//考试总人数

});//扫描返回的数据信息



const ScanStateChange=(state:number)=>{
    scanState.value=state;
}



//关闭弹窗
const CloseDialog = () => {
    showDialog.value = false;
    emit('success');
}




//根据处理后的批次号转换成处理前的批次号
const GetBatchNumber=(batchNumber:any)=>{
    if (!batchNumber) {
        console.warn('批次号为空或未定义');
        return currentBatchNo.value;//返回当前的批次号
    }
    
    const batchStr = batchNumber.toString();
    if (batchStr.length < 3) {
        console.warn('批次号长度小于3位:', batchStr);
        return currentBatchNo.value;//返回当前的批次号
    }
    
    const lastThree = batchStr.slice(-3);
    const parsedNumber = parseInt(lastThree, 10);
    
    if (isNaN(parsedNumber)) {
        console.error('无法解析批次号:', lastThree);
        return currentBatchNo.value;//返回当前的批次号
    }
    console.log("打印最后的批次号",parsedNumber);
    return parsedNumber.toString();
}

//删除批次
const OptionDelete=(row: any) => {
    console.log('删除批次', row);
    
    if(row.scanUserName==currentUserName.value)
    {
        ElMessageBox.confirm('确定要删除该批次吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            // 删除操作
            console.log('删除', row);
            const params={
                examSubjectId:examSubjectId.value,
                batchNo:row.batchNo,
                schoolId:selectSchoolId.value,
            };
            deleteBatch(params).then((res:any)=>{
                if(res.code==200)
                {
                    ElMessage.success("删除成功!")
                    GetScanBatchList(); 
                }
                else
                {
                    ElMessage.error(res.msg);
                }
            })
            
        }).catch(() => {    
            // 取消操作
            console.log('取消删除');
        });
    }
    else
    {
        ElMessage.warning('只能删除自己上传的记录');
    }
}

//跳转到异常详情页
const GotoDetail = (type: number) => {

    // 根据类型跳转到不同的详情页
    switch (type) {
        case 0:
           
            break;
        case 1:
           
            break;
        case -1:
            router.push({
                path: '/exam/scanDetail',
                query: {
                    examSubjectId: examSubjectId.value,
                },
            })
            break;
        }
}

// 打开导入学生名单
const OpenImportStudent = () => {
    showSelectStudent.value=true;
}

// 打开编辑考试名单
const OpenEditExamList = () => {
    router.push({
        path: '/exam/examList',
        query: {
            examSubjectId: examSubjectId.value,
        },
    });
}


//学生名单导入成功
const StudentSuccess = () => {

    HasImportStudent();
}



//查询是否导入了学生名单
const HasImportStudent = async () => { 
    const params = {
      examSubjectId: examSubjectId.value,
      schoolId: 0,//单校 0 
    };
    const res = await hasImportStudent(params);
    console.log("打印是否导入了学生名单",res);
    if(res.code==200)
    {
        isImportStudent.value=res.data;
    }
    else{
        isImportStudent.value=false;
    }
}




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

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

    tableHeight.value = computedHeight;
  });
}; 


//更新扫描张数
const UpdateBatchScanNumber = (batchId: any, scanNumber: Number) => {
    const params={
        id:batchId,
        recordNumber: scanNumber,
    };
    updateScanCount(params).then((res:any)=>{
        if(res.code==200)
        {
           console.log("第"+batchId+"批次更新扫描张数"+scanNumber+"成功", res);
        }

    })
};
// 处理扫描结果
const HandleScanResult = (res: any) => {
   console.log('收到扫描数据', res);
    // 业务逻辑...
    if (res.action == 'uploading') 
    {
            let batchNumber: any = '';
            if (res.batchNumber) 
            {
            batchNumber = GetBatchNumber(res.batchNumber || res.data?.batchNumber);
            }
            const targetItem = tableData.value.find((item: any) => item.batchNo == batchNumber);
            
            if (typeof loadingText !== 'undefined') loadingText.value = "启动扫描仪中";

            ElMessage.success("正在启动扫描仪，请稍后…");
            if (targetItem) 
            {
                targetItem.uploadStatus = 0; //更新上传状态 0 开始上传
            }
    }
    // 开始扫描指令
    if (res.action == 'startScan') 
    {
    
        let batchNumber = GetBatchNumber(res?.batchNumber || res.data?.batchNumber);
        let currentItem = tableData.value.find((item: any) => item.batchNo == batchNumber);
        console.log("打印currentItem", currentItem);
        
        //开始扫描指令
        if (res.code == 200) 
        {
            ElMessage.success("扫描仪启动成功，开始扫描…");
            if(typeof loadingText !== 'undefined') loadingText.value = "正在扫描中";
        }
        
        if (res.code == 502) 
        {
            console.log("开始扫描指令502错误  未检测到纸张或者卡纸", res);
            console.log("打印currentItem", currentItem);
            if (currentItem) {
                currentItem.uploadStatus = 1; //更新上传状态
            }
            if (typeof loadingText !== 'undefined') loadingText.value = ""; //清空上传提示
            isScanning.value = false; //重置扫描状态
            ElMessage.error(res.msg);
        }
        
        if (res.code == 510) 
        {
            console.log("启动扫描失败,上传正在进行中", res);
            isScanning.value = true; //重置扫描状态
            ElMessage.warning(res.msg + '请勿重复点击');
        }
        
        if (res.code == 509) {
            console.log("扫描仪正在使用中", res);

            if (res.msg == '未找到指定的扫描仪') {
                isScanning.value = false; //重置扫描状态
            }

            ElMessage.warning(res.msg + ',请稍后再试!');
            if (currentItem) {
                currentItem.uploadStatus = 1; //更新上传状态
            }
        }
    }
    // 扫描完成指令
    if (res.action == 'uploadFinish') {
        console.log("上传完成uploadFinish 更新上传动画状态", res);
        
        // 修复：直接调用 GetBatchNumber
        let batchNumber = GetBatchNumber(res?.batchNumber || res.data?.batchNumber);
        let targetItem = tableData.value.find((item: any) => item.batchNo == batchNumber);
        
        if (typeof loadingText !== 'undefined') loadingText.value = '正在上传中';
        
        if (targetItem) {
        targetItem.scannedPaperNum = res.scanNumber; //更新扫描张数
        targetItem.failedNumber = res.failedNumber; //更新失败张数
        
        if (typeof UpdateBatchScanNumber === 'function') {
            UpdateBatchScanNumber(targetItem.id, Number(targetItem.scannedPaperNum));
        }
        }
        isScanning.value = false; //重置扫描状态
    }

    if (res.action == 'uploadNumber') {
        console.log("上传完成uploadNumber 更新上传张数", res); 
        // 逻辑已注释，保持原样
    }

    if (res.action == 'scanNumber') {
        console.log("扫描张数scanNumber 更新扫描张数");
        // 修复：直接调用 GetBatchNumber
        let batchNumber = GetBatchNumber(res.batchNumber || res.data?.batchNumber);
        let targetItem = tableData.value.find((item: any) => item.batchNo == batchNumber);
        console.log("打印targetItem", targetItem);
        
        if (targetItem) {
        targetItem.scannedPaperNum = res.number; //更新上传张数
        targetItem.uploadStatus = 0; //更新上传状态 0 开始上传
        }
        
        // 修复：确保 UpdateBatchScanNumber 已定义
        if (targetItem && typeof UpdateBatchScanNumber === 'function') {
            UpdateBatchScanNumber(targetItem.id, Number(targetItem.scannedPaperNum));
        }
    }

  if (res.action == 'loadImage') {
    console.log("加载图片loadImage 获取图片数据", res);
    
    // 修复：reImageList 必须是 ref
    if (typeof reImageList !== 'undefined') {
      reImageList.value = res.data || [];
      reImageList.value.forEach((item: any) => {
        item.uploadStatus = -2; 
        item.uploadProgress = 0; 
      });
    }
    
    let batchNumber = GetBatchNumber(res.batchNumber);
    let targetItem = tableData.value.find((item: any) => item.batchNo == batchNumber);
    
    console.log("打印重新上传图片列表", reImageList.value);
    console.log("打印重新上传的批次Item", targetItem);
    
    if (targetItem) {
      targetItem.uploadStatus = 0; 
    }
    
    if (typeof loadingText !== 'undefined') loadingText.value = '正在上传中';
    if (typeof uploadDialogTitle !== 'undefined') uploadDialogTitle.value = '未上传的图片';
    if (typeof showUploadDialog !== 'undefined') showUploadDialog.value = true;
  }

  if (res.action == 'finish') {
    console.log("图片重传finish指令", res);
    
    let batchNumber = GetBatchNumber(res.batchNumber);
    let targetItem = tableData.value.find((item: any) => item.batchNo == batchNumber);

    let fileIndex = res.fileIndex.split(",");
    console.log("打印fileIndex", fileIndex);
    
    fileIndex.forEach((index: string) => {
      // 修复：reImageList.value
      let reImageItem = reImageList.value.find((item: any) => item.fileIndex == index);
      if (reImageItem) {
        let progress = reImageItem.uploadProgress;
        const interval = setInterval(() => {
          progress += 5;
          if (progress >= 100) {
            progress = 100;
            clearInterval(interval);
            // 修复：Vue3 不需要 $set，直接赋值即可触发响应式
            reImageItem.uploadStatus = res.uploadState;
          }
          reImageItem.uploadProgress = progress;
        }, 100);
      }
    });

    // 修复：reImageCount 可能是 ref 或计算属性
    let currentReImageCount = typeof reImageCount !== 'undefined' ? reImageCount.value : reImageList.value.length;
    
    if (currentReImageCount === 0) {
      if (typeof showUploadDialog !== 'undefined') showUploadDialog.value = false;
      if (targetItem) {
        targetItem.uploadStatus = 1; 
        isScanning.value = false;
        // 修复：确保 GetBatchList 已定义
        if (typeof GetBatchList === 'function') GetBatchList();
      }
    }
  }

  if (res.action == 'getFailedImage') {
    console.log("获取失败图片getFailedImage", res);
    let failedList = res.data || [];
    
    failedList.forEach((item: any) => {
      let batchNumber = GetBatchNumber(item.batchNumber);
      let currentItem = tableData.value.find((item1: any) => item1.batchNo == batchNumber);
      
      if (currentItem) {
        if (item.failedNumber == 0) {
          if (currentItem.scannedPaperNum != currentItem.uploadNum) {
            currentItem.scannedPaperNum = currentItem.uploadNum;
            if (typeof UpdateBatchScanNumber === 'function') {
              UpdateBatchScanNumber(currentItem.id, currentItem.uploadNum);
            }
          }
        } else {
          let number = currentItem.uploadNum + item.failedNumber;
          currentItem.scannedPaperNum = number;
          if (typeof UpdateBatchScanNumber === 'function') {
            UpdateBatchScanNumber(currentItem.id, number);
          }
        }
      }
    });
  }

  if (res.action == 'scanFinishBatch') {
    if (typeof loadingText !== 'undefined') loadingText.value = '本次扫描结束';
    console.log("本批次扫描完成scanFinishBatch 更新扫描张数", res);

  } 

};

onMounted(() => {
    // // 初始化连接
    // scanCommon.init(HandleScanResult);
    // // 监听连接状态
    // scanCommon.watchConnection((isOnline,clientVersion) => {
        
    //     scanClientStates.value=isOnline;
    //     scanClientVersion.value=clientVersion; //客户端版本号
    //     // console.log("客户端版本",clientVersion);
    // });
    if (!examStore.currentExam) {
        console.warn('当前没有选中的考试信息')
        // 可选：如果没有数据，可以重定向回列表页或提示用户
    }
    HasImportStudent();//查询是否导入了学生名单

    CalculateTableHeight();//初始化计算表格高度
  
    // 监听窗口大小变化
    window.addEventListener('resize', CalculateTableHeight);
});
// 卸载时移除监听，防止内存泄漏
onUnmounted(() => {
  window.removeEventListener('resize', CalculateTableHeight);
  // 组件销毁时务必停止，防止内存泄漏和后台重连
//   scanCommon.stop();
});
</script>
 
<style lang="scss" scoped>



</style>