<template>
    <!-- 扫描详情 -->
  <div class="page_list">
    
    <div class="search_content">
        <div class="content_left">
            <el-select  v-model="paramInfo.batchNo"   placeholder="选择批次" @change="GoSearch()" class="select_width" >
                <el-option label="全部批次" value=""></el-option>
                <el-option v-for="item in batchList" :key="item.value"  :label="'批次'+item.label" :value="item.value"></el-option>
            </el-select>
            <el-select  v-model="paramInfo.statusStr"   placeholder="选择状态" @change="GoSearch()" class="select_width" >
                <el-option label="全部状态" value=""></el-option>
                <el-option v-for="item in stateList"
                :key="item.value"
                :label="item.label" :value="item.value"></el-option>
            </el-select>
            <el-input placeholder="考试名称，编号"  v-model="paramInfo.keyWord" @input="GoSearch" @change="GoSearch()" class="input_width" > 
                <el-button @click="GoSearch()"  slot="append" icon="el-icon-search"></el-button>
            </el-input>
        </div>
        <div class="content_right">
            <el-button @click="Refresh" >
                <i class="iconfont icon_shuaxin"></i>刷新
            </el-button>
            

            <el-button @click="GotoScanHome()" type="primary">扫描页面</el-button>
        </div>
    </div>
    <div class="page_jg_20"></div>
    <div class="page_content" >
        <div class="content_table" style="width: 100%">
            <div class="table_header">
                <div class="header_left">
                    <div class="scan_button_header">
                        <el-button @click="ChangeMode('list')" :type="listMode=='list'?'primary':''"><el-icon><Menu /></el-icon> 列表模式</el-button>
                        <el-button @click="ChangeMode('pic')" :type="listMode=='pic'?'primary':''"><el-icon><Picture /></el-icon> 图片模式</el-button>
                    </div>
    
                </div>
                <div class="header_right">
                   
                </div>
            </div>
            <div class="page_jg_20"></div>
            <div class="page_table" v-show="listMode=='list'">
                <el-table :data="tableData" style="width: 100%" :height="tableHeight">
                    <el-table-column type="index" label="序号" width="100" align="center" >
                    </el-table-column>
                    <el-table-column prop="batchNo" label="批次" width="120" align="center">
                        <template v-slot="scope">
                            批次{{ scope.row.batchNo}}
                        </template>
                    </el-table-column>
                    <el-table-column prop="cardNumber" label="考号" width="120" align="center">
                        <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 prop="studentName" label="姓名" width="120" align="center">
                        <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 prop="studentName" label="页数" width="120" align="center">
                        <template v-slot="scope">
                           {{GetPageNumbers(scope.row.scanPictureVOS)}}
                        </template>
                    </el-table-column>
                    <el-table-column prop="date" label="客观题" align="center">
                        <template v-slot="scope">
                            {{GetObjectAnswer(scope.row.objectiveQuestionMap)}}
                        </template>
                    </el-table-column>
                    <el-table-column prop="fullScore" label="状态" width="120" align="center">
                        <template v-slot="scope">
                            <div class="table_row_status">
                                <div class="normal_icon" v-if="scope.row.abnormalType==0"></div>
                                <div class="abnormal_icon" v-else></div>
                                {{GetStateName(scope.row.abnormalType)}}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="操作" width="150" align="center">
                        <template v-slot="scope">
                            <div class="ele_button table_row_button">
                                <span class="btn_editor" @click="OpenViewPaper(scope.row)">查看</span>
                                <!-- <span class="btn_delete" @click="DeleteSingle(scope.row)">删除</span> -->
                            </div>
                    </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="image_list" v-show="listMode=='pic'"  :style="{height:imageHeight+'px'}" >
                <div class="list_img_content" v-loading="loading" element-loading-text="加载中……" element-loading-spinner="el-icon-loading" element-loading-background="#ffffff">
                    <div v-for="(image, index) in imageData" :key="'image_'+index" class="list_img_item">
                        <div class="item_batch_name">
                            <span><el-checkbox  v-model="image.checked" style="margin-right: 5px;"></el-checkbox>  批次{{image.batchNo}}-{{image.seqNumber}}     </span>
                            
                            <!-- <span class="" v-if="image.abnormalType==0">正常</span> -->
                            <span class="name_abnormal" v-if="image.abnormalType==4">定位异常</span>
                            <span class="name_abnormal" v-if="image.abnormalType==5">缺页异常</span>
                            <span class="name_abnormal" v-if="image.abnormalType==1 || image.abnormalType==2 || image.abnormalType==3">考号异常</span>
                        </div>
                        <div class="item_batch_img" :class="image.abnormalType!=0 && image.abnormalType!=null?'item_batch_img_error':''" >
                            <img :src="image.recognizeUrl" alt=""  loading="lazy"></img>
                            <div class="button_group">
                                <div class="pic_button_view" @click="OpenViewPaper(image)">
                                    <i class="iconfont icon_xianshimima"></i>查看
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="page_pagination">
                <el-pagination background
                    :page-size="pageInfo.pageSize"
                    :pager-count="11"
                    layout="prev, pager, next"
                    :total="pageInfo.total"
                    :current-page="pageInfo.pageNum" 
                    @current-change="HandlePageChange"
                />
            </div>
        </div>
    </div>
    <PaperView v-model="showPaperDialog" :imageList="PaperImageList"></PaperView>
  </div>
</template>
<script lang="ts" setup>
import { useExamStore } from '@/store/exam'
import { useRouter,useRoute  } from 'vue-router'
import { onMounted ,ref,computed,nextTick,onUnmounted} from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus'

import { getBatchDetailList,getBatchDetailImage } from '@/api/exam'
import PaperView from './components/PaperView.vue'

// 定义选项接口类型
interface OptionItem {
  label: string
  value: string | number
  sort: number
}
// 实例化 Store
const examStore = useExamStore()
const router = useRouter()
const route = useRoute() // 2. 获取 route 实例
// 考试科目 ID
const examSubjectId = computed(() => {
  return examStore.currentExam?.id
})//计算属性

const paramInfo=ref({
    batchNo:'',
    statusStr:'',//状态
    keyWord:''
})//筛选数据
const pageInfo=ref({
    pageNum:1,
    pageSize:10,
    total:0
})//分页数据

const batchList = ref<OptionItem[]>([])
const stateList = ref<OptionItem[]>([])


const listMode=ref('list');

const tableData=ref([]);
const imageData=ref([]);//图片数据
const loading=ref(false); //加载状态


const tableHeight=ref(500);
const imageHeight=ref(500);


const isImportStudent=ref(false);//是否导入了学生名单
const showSelectStudent=ref(false);//是否显示选择学生名单弹窗
const showPaperDialog=ref(false);//显示图片详情弹窗
const PaperImageList=ref([]);//图片列表
// 打开导入学生名单
const OpenImportStudent = () => {
    showSelectStudent.value=true;
}

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

//获取扫描批次的页数
const GetPageNumbers=(scanPictureVOS:any):string=>{
    if (scanPictureVOS && Array.isArray(scanPictureVOS) && scanPictureVOS.length > 0) {
        return scanPictureVOS
            .filter(item => item.pageNo !== -1)
            .map(item => item.pageNo === 99 ? '-' : item.pageNo)
            .join(',');
    }
    return '-';
}

//将答案对象转成字符串
const GetObjectAnswer=(obj:any):string=>{
            
    let str=Object.entries(obj).map(([key, value]) => {
        return `${key}:${value}`
    }).join(' ')
    return str
}

//获取状态名称
const GetStateName=(value:number):string=>{
    console.log("打印状态值",value);
                        
    let stateName='';
    if(value==0)
    {
        stateName='已上传';
    }
    else if(value==1)
    {
        // stateName='考号未识别出来';
        stateName='考号异常';
    }
    else if(value==2)
    {
        // stateName='无此考生';
        stateName='考号异常';
    }
    else if(value==3)
    {
        // stateName='考号重复';
        stateName='考号异常';
    }
    else if(value==4)
    {
        stateName='定位异常';
    }
    else if(value==5)
    {
        stateName='缺页异常';
    }
    return stateName;
}


//切换模式
const ChangeMode = (mode: string) => {
    listMode.value = mode;
    LoadData();
}

//加载数据
const LoadData = () => {
    if(listMode.value=='list')
    {
        GetScanDetailList();
    }
    else if(listMode.value=='pic')
    {   
        GetScanDetailImage();
    }
    
}




//查看图片
const OpenViewPaper = (image:any) => {

    console.log("查看图片",image);
    let imageUrl=image.scanPictureVOS[0].recognizeUrl;
    PaperImageList.value.push(imageUrl);
    showPaperDialog.value=true;
}

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

//搜索
const GoSearch = () => { 

}

//刷新
const Refresh=() => {
    GetScanDetailList();
}


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

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

//获取扫描详情 列表模式
const GetScanDetailList = async () => {
    const params = {
      examSubjectId: examSubjectId.value,
      batchNo:paramInfo.value.batchNo,//批次号
      statusStr:paramInfo.value.statusStr,//状态
      nameCode:paramInfo.value.keyWord,//搜索条件 姓名 考号
      schoolId: 0,//单校 0 
      pageNum:pageInfo.value.pageNum,//当前页码
      pageSize:pageInfo.value.pageSize,//每页条数
    };
    const res = await getBatchDetailList(params);
    console.log("打印批次详情列表",res);
    if(res.code==200)
    {
       batchList.value=res.data.batchSelects;
       stateList.value=res.data.statusSelects;
       tableData.value=res.data.pageResult.records;
       pageInfo.value.total=Number(res.data.pageResult.total);
    }
    else
    {
        ElMessage.error(res.msg);
    }
}

//获取扫描详情 图片模式
const GetScanDetailImage = async () => {
    const params = {
      examSubjectId: examSubjectId.value,
      batchNo:paramInfo.value.batchNo,//批次号
      statusStr:paramInfo.value.statusStr,//状态
      nameCode:paramInfo.value.keyWord,//搜索条件 姓名 考号
      schoolId: 0,//单校 0 
      pageNum:pageInfo.value.pageNum,//当前页码
      pageSize:pageInfo.value.pageSize,//每页条数
    };
    const res = await getBatchDetailImage(params);
    console.log("打印批次详情列表",res);
    if(res.code==200)
    {
      
       imageData.value=res.data.records;
       pageInfo.value.total=Number(res.data.total);
    }
    else
    {
        ElMessage.error(res.msg);
    }
}



onMounted(() => {

    // 3. 获取地址栏参数 batchNo 并赋值
    if (route.query.batchNo) {
        paramInfo.value.batchNo = route.query.batchNo as string;
    }
    
    LoadData();//加载数据
    CalculateTableHeight();//初始化计算表格高度
    // 监听窗口大小变化
    window.addEventListener('resize', CalculateTableHeight);
})
// 卸载时移除监听，防止内存泄漏
onUnmounted(() => {
  window.removeEventListener('resize', CalculateTableHeight);

});
</script>
 
<style lang="scss" scoped>

.page_list
{
    width: 100%;
    height: 100%;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-sizing: border-box;

}

.image_list {
    width: 100%;
    overflow: auto;

    .list_img_content {
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
      /* 顶部对齐 */
      box-sizing: border-box;
      flex-wrap: wrap;
      gap: 16px;

      .list_img_item {
        /* 基础宽度 - 每行7个 */
        flex: 0 0 calc((100% - 16px * 6) / 7);

        /* 最小宽度 */
        min-width: 160px;
        /* 保持宽高比（可选） */
        // aspect-ratio: 1/1;
        // margin-right: 15px;
        // margin-bottom: 16px;
        /* 内容样式 */

        height: auto;

        // margin-right: 13px;
        .item_batch_name {
          width: 100%;
          font-size: 14px;
          color: #666666;
          text-align: left;

          display: flex;
          justify-content: space-between;
          line-height: 30px;

          .name_abnormal {
            color: #F56C6C;
          }
        }

        .item_batch_img {
          width: 100%;
          height: auto;
          padding: 8px;
          box-sizing: border-box;
          background-color: #F0F4F8;
          border-radius: 6px 6px 6px 6px;
          border: 1px solid #EBEEF5;
          display: flex;
          justify-content: center;
          position: relative;

          img {
            width: 100%;
            height: auto;
            object-fit: cover;
            z-index: 9;
          }

        }

        .item_batch_img_error {
          border: 1px solid #F56C6C !important;
        }

        .item_batch_img:hover .button_group {
          display: flex;
          justify-content: center;
          align-items: center;
        }

        .button_group {
          position: absolute;

          width: 100%;
          height: 100%;
          z-index: 10;
          top: 0px;
          left: 0;
          background: rgba(0, 0, 0, 0.4);
          display: none;
          align-items: center;
          justify-content: center;
          gap: 16px;
          z-index: 999;

          .pic_button_view {
            width: 68px;
            height: 34px;
            text-align: center;
            line-height: 34px;

            cursor: pointer;
            background-color: rgba(255, 255, 255, 1);
            border: 1px solid rgba(220, 223, 230, 1);
            border-radius: 4px;
            color: #666666;

            i {
              margin-right: 5px;
            }

            font-size: 14px;
          }


        }
      }

      @media (max-width: 1458px) {
        .list_img_item {
          flex: 0 0 calc((100% - 16px * 5) / 6);
        }

      }

      @media (max-width: 1280px) {
        .list_img_item {
          flex: 0 0 calc((100% - 16px * 4) / 5);
        }

      }

      @media (max-width: 1109px) {
        .list_img_item {
          flex: 0 0 calc((100% - 16px * 3) / 4);
        }

      }

      @media (max-width: 940px) {
        .list_img_item {
          flex: 0 0 calc((100% - 16px * 2) / 3);
        }

      }


    }




  }

</style>