<template>
  <div v-loading="!paperInfo.id" class="v-page print-paper">
    <div style="max-width: 210mm; min-width: 210mm">
      <div id="paperView">
        <div class="seal">
          <div class="examinee-info">
            <p v-for="(item, index) in examineeInfo" :key="index">
              <span style="font-size: 15px; font-weight: bold">{{
                item.value
              }}</span>
            </p>
          </div>
          <div class="seal-title">
            <div>线</div>
            <div>封</div>
            <div>密</div>
          </div>
        </div>
        <ExercisePerviewPaper
          class="paper-perview"
          :questions="questions"
          :title="paperInfo?.title"
          :mode="mode"
          ref="printRef"
        >
          <template v-slot:title>{{ paperInfo?.title }}</template>
          <template v-slot:otherInfo>
            <div class="exam-base-explain">
              全卷满分：{{ paperInfo.totalScore }}分，考试时间：{{
                paperInfo.paperDuration
              }}分钟
            </div>
            <div class="exam-base-notice" v-if="checkTypeInfo.info?.考生须知">
              <div class="notice-title">考生须知</div>
              <div class="notice-content">
                <p
                  v-for="(item, index) in notice"
                  :key="index"
                  style="word-break: break-all"
                >
                  {{ index + 1 }}：{{ item.value }}
                </p>
              </div>
            </div>
            <div
              class="exam-question-type-score"
              v-if="checkTypeInfo.info?.总评分"
            >
              <table border="1">
                <thead>
                  <th
                    class="type-score-item"
                    v-for="(item, index) in questionsClssify.classify"
                    :key="index"
                  >
                    {{ item.title }}
                  </th>
                  <th class="type-score-item">总分</th>
                </thead>
                <tbody>
                  <td
                    class="type-score-item"
                    v-for="(item, index) in questionsClssify.classify"
                    :key="index"
                  >
                    {{ item.userScore }}
                    <br />
                    <!-- {{ item.score }} -->
                  </td>
                  <td class="type-score-item">
                    {{
                      questionsClssify.classify?.reduce((prev, item) => {
                        if (typeof item.userScore === "undefined") {
                          return "";
                        }
                        return (prev += item.userScore);
                      }, 0)
                    }}
                    <br />
                    <!-- {{
                      questionsClssify.classify?.reduce((pre, item) => {
                        return item.score + pre;
                      }, 0)
                    }} -->
                  </td>
                </tbody>
              </table>
            </div>
          </template>
        </ExercisePerviewPaper>
      </div>
    </div>
    <div class="print-toolbar">
      <div>
        <div class="form-item flex-center">
          <div class="form-item-label">试卷类型：</div>
          <div class="form-item-content">
            <el-select
              v-model="printType"
              @change="changeType"
              size="mini"
              placeholder="请选择打印类型"
            >
              <el-option
                v-for="item in printData"
                :key="item.id"
                :label="item.type"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="form-item">
          <div class="form-item-label">试卷信息：</div>
          <div class="form-item-content">
            <p
              v-for="(item, key) in checkTypeInfo.info"
              :key="item"
              style="margin-bottom: 10px; white-space: nowrap"
            >
              <el-radio value="1" label="1"
                ><span
                  style="
                    color: #555555;
                    margin-right: 10px;
                    width: 90px;
                    display: inline-block;
                  "
                  >{{ key }}</span
                >
                <el-button
                  @click="toEditorInfo(key)"
                  style="font-size: 14px; padding: 0"
                  type="text"
                  size="mini"
                  v-if="['考生信息填写', '考生须知'].includes(key)"
                  >编辑</el-button
                >
              </el-radio>
            </p>
          </div>
        </div>
        <div class="form-item">
          <div class="form-item-label">试卷排版：</div>
          <div class="form-item-content">
            <el-radio-group v-model="composing">
              <el-radio :label="0" style="margin-bottom: 10px">单页版</el-radio>
              <el-radio :label="1">双页版</el-radio>
            </el-radio-group>
          </div>
        </div>
      </div>
      <el-button type="primary" style="width: 100%" @click="toPrint(false)"
        >打印</el-button
      >
      <el-button type="primary" style="width: 100%;margin:10px 0 0 0;" @click="toPrint(paperInfo)"
        >导出</el-button
      >
    </div>
    <DialogLayout
      :title="editorInfo.name"
      :actionBarOption="{
        noCencel: true,
        noConfirm: true,
      }"
      :visible="editorInfo.name.length"
      @onCancel="editorInfo = { name: '', key: '' }"
    >
      <div style="text-align: center">
        <p
          class="editorInfo-item"
          v-for="(item, index) in editorInfo.data"
          :key="index"
        >
          <el-input v-model="item.value" size="mini"></el-input>
          <el-button
            :disabled="index === 0"
            type="text"
            :style="{
              'margin-left': '10px',
              color: index === 0 ? '#ccc' : '#f56c6c',
            }"
            @click="delEditorInfo(index)"
            >删除</el-button
          >
        </p>
        <el-button type="primary" @click="addEditorInfo">添加</el-button>
      </div>
    </DialogLayout>
    <DialogLayout
      :visible="isCheckExam"
      title="选择试卷"
      @onCancel="isCheckExam = false"
      @onConfirm="selectExam"
    >
      <SelectExamPaper v-if="$store.user.baseRole === 3"></SelectExamPaper>
      <HumanEvaluation :column="paperColumn" v-else></HumanEvaluation>
    </DialogLayout>
  </div>
</template>

<script>
import ExercisePerviewPaper from '@/views/statistic/components/ExercisePerviewPaper.vue'
import { getPaperInfoByIdApi } from '@/api/assessment-evaluation/paper'
import { DialogLayout } from '@/components/layout'
import SelectExamPaper from './SelectExamPaper.vue'
import HumanEvaluation from '@/views/assessment-evaluation/human-evaluation/index.vue'
import { getOnlineExamResultApi } from '@/api/assessment-evaluation/onlineTest'

export default {
  components: {
    ExercisePerviewPaper,
    DialogLayout,
    SelectExamPaper,
    HumanEvaluation
  },
  data: () => ({
    // 试卷ID
    paperId: null,
    // 试卷信息
    paperInfo: {},
    // 试题列表
    questions: [],
    // 隐藏或展示选取试卷的弹窗
    isCheckExam: false,
    // 打印类型
    printType: null,
    // 编辑考生信息和考生信息切换
    editorInfo: { name: '', key: '', data: [], max: 0 },
    // 单双页
    composing: 0,
    // 试题分类后的数据
    questionsClssify: {},
    // 选中的打印模式详细信息
    checkTypeInfo: {},
    // 打印模式对应的组件状态
    mode: 2,
    // 路径参数
    query: {},
    // 几种打印模式
    printData: [
      {
        type: '正式试卷',
        id: 1,
        mode: 2,
        info: {
          考生信息填写: true,
          考生须知: true,
          考试时间及总分: true,
          试卷分类: true,
          总评分: true,
          题型评分: true,
          分割线: true
        }
      },
      {
        type: '练习试卷',
        id: 2,
        mode: 2,
        info: {
          考生信息填写: true,
          考试时间及总分: true,
          试卷分类: true,
          总评分: true,
          题型评分: true,
          分割线: true
        }
      },
      {
        type: '背题试卷',
        id: 3,
        mode: 4,
        info: {
          考生信息填写: true,
          考试时间及总分: true,
          试卷分类: true,
          // 总评分: true,
          // 题型评分: true,
          分割线: true,
          答案: true,
          解析: true
        }
      },
      {
        type: '考试试卷',
        id: 4,
        mode: 1,
        info: {
          考生信息填写: true,
          考试时间及总分: true,
          试卷分类: true,
          总评分: true,
          题型评分: true,
          分割线: true,
          答案: true,
          解析: true,
          评分: true,
          评语: true
        }
      }
    ],
    // 基础的考生信息
    examineeInfo: [
      { value: '姓名__________' },
      { value: '班级__________' },
      { value: '证件号__________' }
    ],
    // 考生须知
    notice: [
      {
        value:
          '考前三十分钟，考生需持符合报考规定的并与准考证显示信息一致的有效证件，进入规定的考场。'
      },
      { value: '考生入场后，按号入座，将本人《准考证》放在课桌上，以便核验。' },
      {
        value:
          '笔试开考10分钟内，允许迟到考生进入考场参加考试，考试结束时间按照统一规定结束。开考10分钟后，禁止迟到考生入场考试。提前离场考生离场后不得进场续考。考试最后十分钟内考生不得离场。'
      },
      {
        value:
          '考试期间考生可携带物品：签字笔、铅笔、橡皮、二十四色彩笔（包含黑色、蓝色、棕色、绿色、灰色、橙色、粉色、紫色、红色、黄色）铅笔盒、塑料瓶装水、药品、纸巾和准考证。'
      }
    ],
    // 选取试卷时的表头
    paperColumn: [
      {
        prop: 'title',
        label: '考试名称',
        'min-width': 125,
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'examStartTime',
        label: '开始时间',
        'min-width': 130,
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'examEndTime',
        label: '结束时间',
        'min-width': 130,
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'totalScore',
        label: '考试总分',
        'min-width': 80,
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'passScore',
        label: '及格分',
        'min-width': 80,
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'gradedCount',
        label: '已评分人数',
        'min-width': 90,
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'ungradedCount',
        label: '未评分人数',
        'min-width': 90,
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'action',
        label: '操作',
        //  width: 350,
        width: 120,
        align: 'center',
        'show-overflow-tooltip': true
      }
    ]
  }),
  created () {
    const query = this.$route.query
    this.query = query
    this.paperId = +this.$route.params.paperId
    // 判断是否为考试试卷模式
    if (query.examIdPaperId) {
      this.printType = 4
      this.changeType(4)
      return
    }
    // 如果没有试卷信息则跳转选择
    if (!this.paperId) {
      this.$router.push('/assessment-evaluation/examination-paper-manage')
    }
    this.printType = 1
    this.changeType(1)
    this.getPaperInfo(this.paperId)
  },
  mounted () {},
  methods: {
    /**
     * 获取试卷信息
     * @param {number} id
     * @returns
     */
    async getPaperInfo (id) {
      const { data } = await getPaperInfoByIdApi(id)
      this.questions = data.questionInfo.fixdQuestions.concat(
        data.questionInfo.randQuestions
      )
      this.paperInfo = data
      this.questionsClssify = this.formatQuestions(this.questions)
      console.log(this.questions, data, this.questionsClssify, '1123123123')
    },
    /**
     * 编辑考生信息或考生须知
     * @returns
     */
    toEditorInfo (key) {
      this.editorInfo = {
        name: key,
        key: key === '考生信息填写' ? 'examineeInfo' : 'notice',
        max: key === '考生信息填写' ? 5 : 5
      }
      this.$set(this.editorInfo, 'data', this[this.editorInfo.key])
      console.log(this.editorInfo, '111111')
    },
    /**
     * 调用打印接口
     * @returns
     */
    toPrint (exportInfo) {
      this.$html2Pdf('paperView', exportInfo)
    },
    /**
     * 切换打印模式
     * @param {number} e
     * @returns
     */
    changeType (e) {
      // 如果当前为第四打印模式 需要判断是否已经选中了考生答过的试卷
      if (e === 4 && !this.query.examIdPaperId) {
        this.isCheckExam = true
        return
      } else if (e === 4 && this.query.examIdPaperId) {
        getOnlineExamResultApi(this.query.examIdPaperId)
          .then((res) => {
            this.paperInfo = res.data.exam
            this.questions = res.data.questions
            this.questionsClssify = this.formatQuestions(this.questions)
          })
          .finally((_) => {
            this.paper_list_loading = false
          })
        // 如果非第四打印模式并且未选中试卷 则去试卷页面选择
      } else if (!this.paperId) {
        this.$router.push('/assessment-evaluation/examination-paper-manage')
      } else if (this.paperId) {
        this.getPaperInfo(this.paperId)
      }
      this.isCheckExam = false
      this.checkTypeInfo = this.printData.find((item) => {
        return item.id === e
      })
      this.mode = this.checkTypeInfo.mode
    },
    // 处理试题信息
    formatQuestions (questionList) {
      const resQ = questionList.reduce(
        (prev, item) => {
          const index = prev.classify.findIndex((j) => j.title === item.type)
          if (index === -1) {
            prev.classify.push({
              title: item.type,
              score: item.itemScore || item.score || 0,
              userScore:
                typeof item.userScore !== 'undefined'
                  ? item.userScore
                  : undefined
            })
          } else {
            prev.classify[index].score += item.itemScore || item.score || 0
            if (typeof item.userScore !== 'undefined') {
              prev.classify[index].userScore += item.userScore
            }
            // console.log(item.userScore)
          }
          if (Object.keys(prev.questions).includes(item.type)) {
            prev.questions[item.type].push(item)
          } else prev.questions[item.type] = [item]
          return prev
        },
        { classify: [], questions: {} }
      )
      return resQ
    },
    // 删除编辑的信息
    delEditorInfo (index) {
      this.editorInfo.data.splice(index, 1)
    },
    addEditorInfo () {
      const { max, data } = this.editorInfo

      if (max && max <= data.length) {
        this.$message.error('最多添加五条信息')
        return
      }

      data.push({ value: '' })
    }
  }
}
</script>

<style lang="scss" scoped>
.print-paper {
  display: flex;
  ::v-deep .question-title {
    font-weight: bold;
  }
  > div {
    height: 100%;
    overflow: auto;
    flex: 1;
  }
  .print-toolbar {
    max-width: 250px;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-left: 20px;
  }

  #paperView {
    display: flex;
    width: 100%;
    padding-right: 10mm;
    overflow: hidden;
  }
  .paper-perview {
    flex: 1;
    overflow: hidden;
  }
  .seal {
    height: 297mm;
    // width: 80px;
    max-width: 50px;
    min-width: 50px;
    position: relative;
    border-right: 1px dashed #464646;
    margin-right: 30px;
  }
  .seal-title {
    position: absolute;
    right: -7.5px;
    height: 100%;
    font-size: 15px;
    font-weight: bold;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    > div {
      transform: rotate(-90deg);
      background-color: #fff;
    }
  }
  .examinee-info {
    height: 100%;
    display: flex;
    overflow: hidden;
    flex-direction: column;
    position: absolute;
    white-space: nowrap;
    padding-top: 20px;
    justify-content: space-around;
    > p {
      transform: rotate(-90deg);
      transform-origin: left top;
    }
  }
  .flex-center {
    align-items: center;
  }
  .form-item {
    display: flex;
    margin-bottom: 10px;
    // align-items: center;
    font-size: 15px;
    .form-item-label {
      font-weight: 700;
      white-space: nowrap;
      // width: 110px;
    }
    .form-item-content {
      flex: 1;
    }
  }
  .exam-base-explain {
    text-align: center;
    font-weight: bold;
    margin-bottom: 10px;
  }
  .exam-base-notice {
    width: 100%;
    display: flex;
    margin-bottom: 10px;
    .notice-content,
    .notice-title {
      border: 1px solid #aeaeae;
    }
    .notice-title {
      display: flex;
      align-items: center;
      width: 100px;
      font-size: 25px;
      padding: 14px 24px;
      border-right: none;
    }
    .notice-content {
      padding: 5px;
      flex: 1;
      font-size: 12px;
      overflow: hidden;
      color: black;
      p {
        margin-bottom: 3px;
      }
    }
  }
  .exam-question-type-score {
    display: flex;
    // width: 100%;
    justify-content: center;
    table {
      border-collapse: collapse;
      .type-score-item {
        width: 100px;
        padding: 10px 0;
        text-align: center;
      }
    }
  }
}
.editorInfo-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
</style>
