<template>
  <el-dialog title="预览答题卡"  :visible.sync="showDialog" class="page_full_dialog" fullscreen height="100%">
      <div class="page_header">
          <div class="back_button" @click="GoBack()">
              <i class="iconfont icon_return"></i>返回
          </div>
          <div class="header_title">
            {{ pageTitle }}{{ studentCode }}<span class="header_title_tip">(右键点击图片另存为可保存图片到本地)</span>
          </div>
      </div>
      <div class="dialog_paper">
        <div class="paper_content">
          <div class="canvas_button">
            <div :class="currentIndex==0?'disable_button_item':'button_item'"  @click="LastPaper()">
              <i class="el-icon-arrow-left"></i>
            </div>
          </div>
          <div class="canvas_image" v-loading="isLoading" element-loading-text="加载中……" element-loading-spinner="el-icon-loading" element-loading-background="#ffffff">
            <PaperImage :paperImgUrl="currentPaperUrl"  :drawData="currentDrawData" :usedCardType="usedCardType" :downLoadName="currentDownLoadName"></PaperImage>
          </div>
          <div class="canvas_button">
            <div :class="currentIndex==paperImageList.length-1?'disable_button_item':'button_item'" @click="NextPaper()">
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </div>
        <div class="paper_question">
          <div class="area_table">
            <el-table :data="questionList" border ref="questionTable" :max-height="questionTableHeight">
                <el-table-column label="小题名称" prop="questionName" align="center">
                  <template slot-scope="scope">
                    {{ scope.row.questionName }}
                  </template>
                </el-table-column>
                <el-table-column label="满分/答案" align="center">
                  <template slot-scope="scope">
                    {{ scope.row.fullScore }}<span v-if="scope.row.questionAnswer">/{{ scope.row.questionAnswer }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="得分/答案" align="center">
                  <template slot-scope="scope">
                    <div :class="scope.row.fullScore==scope.row.score?'':'question_score'">
                    <template v-if="questionDisplayType === 0">{{ scope.row.score }}</template>
                    <template v-if="questionDisplayType === 1">
                      <img v-if="scope.row.correctType==0" src="@/assets/icon/icon_all_wrong.svg" style="width: 12px;" />
                      <img v-else-if="scope.row.correctType==2" src="@/assets/icon/icon_all_right.svg" style="width: 12px;" />
                      <img v-else src="@/assets/icon/icon_half_right.svg" style="width: 12px;" />
                    </template>
                    <span v-if="scope.row.value">/{{ scope.row.value }}</span>
                    </div>
                  </template>
                </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      
  </el-dialog>
</template>
<script>

import PaperImage from '@/components/PaperImage.vue';//学生试卷组件
import {getApiName} from '@/utils/common';
export default {
    name: 'StudentPaper',//学生试卷组件
    components:
    {
      PaperImage,
    },

    props: {
        paperInfo:
        {
            type: Object,
            default: () => { }
        },//试卷信息

        pageTitle:
        {
            type: String,
            default: ''
        },//试卷标题

        value: {
            type: Boolean,
            required: true,
        },//是否显示弹窗
        currentPageIndex:{//默认显示第一页答题卡
          type: Number,
          required: 0,
        }
        
    },
    computed: {

        showDialog: {
            get() {
                return this.value;
            },
            set(val) {
                this.$emit("input", val);
            },
        },
    },
    watch:{
        value(newVal) 
        {
          if (newVal) {
            this.currentIndex=this.currentPageIndex;
            this.GetStudentPaperInfo();
          }
        }
    },
    data() {
        return {
           paperImageList: [],//学生试卷图片列表
           currentIndex: 0,//当前学生试卷图片索引
           currentPaperUrl: '',//当前学生试卷图片地址
           currentDownLoadName: '',//当前学生试卷图片下载名称
           currentDrawData:[],//当前学生试卷答题标记数据
           questionList: [],//学生试卷题目列表
           questionDisplayType:'',
           questionTableHeight: 0,//学生试卷题目列表高度
           usedCardType:null,//学生系统卡类型
           isLoading:false,//是否正在加载中
           studentName: '',//学生姓名
           studentCode:''
        }
    },
    created() {
       
    },
    mounted() {
      // 禁用鼠标右键
      document.addEventListener('contextmenu', this.DisableRightClick);
      
       
    },
    beforeDestroy() 
    {
      document.removeEventListener('contextmenu', this.DisableRightClick);
    },
    methods: {

      // 禁用右键菜单的方法
      DisableRightClick(event) {
        event.preventDefault();
        return false;
      },

      
      // 返回
      GoBack()
      {
        this.showDialog=false;
      },

      //上一个试卷
      LastPaper()
      {
        console.log("上一个试卷");
        if (this.currentIndex > 0) 
        {
          this.currentIndex--;
          this.UpdateCurrentPaperData();
          console.log("切换到上一张试卷，当前索引：", this.currentIndex);
        } else {
          console.log("已经是第一张试卷");
          // 可以添加提示信息，如：this.$message.warning('已经是第一张试卷');
        }
      },

      //下一个试卷
      NextPaper()
      {
        console.log("下一个试卷");
        if (this.currentIndex < this.paperImageList.length - 1) 
        {
          this.currentIndex++;
          this.UpdateCurrentPaperData();
          console.log("切换到下一张试卷，当前索引：", this.currentIndex);
        } else {
          console.log("已经是最后一张试卷");
          // 可以添加提示信息，如：this.$message.warning('已经是最后一张试卷');
        }
      },


      // 获取学生试卷详情信息
      GetStudentPaperInfo()
      {
        if(this.paperInfo.examId!='' && this.paperInfo.subjectCode!=null)
        {
          this.isLoading=true;
          this.$api.reportStudent[getApiName()].findStudentCard(this.paperInfo).then(res=>{
            console.log("打印学生试卷详情信息",res);
            
            

            if(res.code==200 && res.data)
            {
              //this.paperImageList=res?.data?.pageVOS || [];
              // 过滤掉picUrl为空的数据
              this.paperImageList = (res.data.pageVOS || []).filter(item => item.picUrl && item.picUrl.trim() !== '');
              const studentCode =  res?.data?.studentCode ?? '';
              this.studentCode = studentCode ?`【${studentCode}】`:'';
              this.usedCardType=res?.data?.usedCardType ?? 2;
              // 重置索引并更新当前试卷数据
              // this.currentIndex = 0;
              this.UpdateCurrentPaperData();
              console.log("打印学生试卷当前图片地址",this.currentPaperUrl);

              // 合并所有试卷图片中的题目列表
              // let allQuestions = [];
              //先添加总分数据
              let totalScore = {
                questionName: '总分',
                fullScore: res?.data?.fullScore || 150,
                score: res?.data?.levelName ?? res?.data?.totalScore,
                displayType:res.data.displayType,//显示类型 0-分数 1-对错 2-等级
                displayName: res.data.displayName,//显示值
                correctType: res.data.correctType,//显示对错的时候 0-错 1-半对 2-全对
                questionAnswer: '',
                answer: '',
                samplingPosition:"{\"x\":195,\"y\":247,\"page\":1}",
              };
              if (this.paperImageList.length > 0 && this.paperImageList[0].questionVOS) {
                this.paperImageList[0].questionVOS.unshift(totalScore);
              }
              // this.paperImageList.forEach(item => {
              //   if (item.questionVOS && item.questionVOS.length > 0) {
              //     allQuestions = allQuestions.concat(item.questionVOS);
              //   }
              // });
              
              this.questionList = res?.data?.studentAnswerBOS || [];
              this.questionDisplayType = res?.data?.questionDisplayType;
              console.log("合并后的题目列表", this.questionList);
              
              this.CalculateTableHeight();//计算表格高度
              this.$nextTick(() => {
                this.isLoading=false;
              });
            }
            else
            {
              this.currentPaperUrl="";//清空试卷地址
              this.currentDrawData=[];//清空试卷答题数据
              this.paperImageList = [];
              this.currentIndex = 0;
              this.questionList = [];
              this.questionDisplayType = '';
              this.studentCode = '';
              this.questionTableHeight='';
              this.$nextTick(() => {
                this.isLoading=false;
              });
            }
          })
        }
        
      },

      

      // 计算表格高度（更精确的方式）
      CalculateTableHeight() 
      {
        this.$nextTick(() => {
          const paperQuestionElement = this.$el.querySelector('.paper_question');
          const tableHeaderElement = this.$el.querySelector('.page_header');
          
          if (paperQuestionElement && tableHeaderElement) {
            // 获取页面相关元素的高度
            const pageHeaderHeight = tableHeaderElement.offsetHeight || 40;
            const paperQuestionPadding = 40; // 20px * 2 padding
            // 计算可用高度
            const availableHeight = window.innerHeight - 65 - 80;
            // 设置表格最大高度
            this.questionTableHeight = availableHeight;
            console.log('精确计算的表格高度:', this.questionTableHeight);

          } 
          else 
          {
            // 备用计算方式
            const availableHeight = window.innerHeight - 65 - 40 - 40;
            this.questionTableHeight = availableHeight;
          }
        });
      },

      // 更新当前试卷数据的公共方法
      UpdateCurrentPaperData() 
      {
        if (this.paperImageList.length > 0 && this.currentIndex < this.paperImageList.length) {
          this.currentPaperUrl = this.paperImageList[this.currentIndex].picUrl;
          this.currentDrawData = this.paperImageList[this.currentIndex].questionVOS || [];
          this.currentDownLoadName = this.pageTitle+'答题卡第'+(this.currentIndex + 1) + '页'; // 重置下载名称
          //兼容旧的数据
          if(this.paperImageList[this.currentIndex].useType)
          {
            this.usedCardType=this.paperImageList[this.currentIndex].useType;//卡类型需要调整为从此页获取
          }
        } else {
          // 处理边界情况
          this.currentPaperUrl = '';
          this.currentDrawData = [];
          this.currentDownLoadName = '';
        }
      },








      


    }
}
</script>
<style lang="scss" scoped>
.dialog_paper
{
  width: 100%;
  height: calc(100vh - 65px);
  background: #F0F4FB;
  overflow: hidden;

  display: flex;
  justify-content: space-between;
  padding: 20px;
  box-sizing: border-box;
  .paper_content
  {
    width: calc(100% - 340px);
    height: 100%;
    display: flex;
    justify-content: flex-start;
    .canvas_button
    {
      width: 48px;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      .button_item
      {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        background: rgba(0,0,0,0.1);
        color:#999999;
        font-size: 24px;
        line-height: 48px;
        text-align: center;
        cursor: pointer;
      }
      .disable_button_item
      {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        background: rgba(0,0,0,0.1);
        color:#C0C4CC;
        font-size: 24px;
        line-height: 48px;
        text-align: center;
      }
    }
    
    .canvas_image
    {
      width: calc(100% - 88px - 40px);
      height: 100%;
      margin: auto;
      // background-color: green;
    }
  }

  .paper_question
  {
    width: 320px;
    height: 100%;
    background: #FFFFFF;
    border-radius: 10px;
    border: 1px solid #EBEEF5;
    padding: 20px;
    box-sizing: border-box;


   
    .question_score
    {
      color:#F56C6C;
      display: flex;
      height: 100%;
      align-items: center;
      justify-content: center;
    }
  }
}


</style>
