<template>
  <div class="app-container" v-loading="submitLoading">
    <div class="answer_title">
      <div class="answer_title_info">
        <span>{{ mxGlobal.TailingClassName(className) }}</span>
        <span>{{ studentName }}</span>
      </div>
      <div class="answer_title_name">
        {{ dataDetail.name }}
        <span style="font-size: 14px; color: #999">{{ dataDetail.scoringType == 1 ? '自阅卷' : '老师阅卷' }}</span>
        <div style="font-size: 14px;color:red;line-height: 24px;margin-top: 5px;" v-if="currentQuestion.questionId">
          题目编号与分数：{{ currentQuestion.questionId }} （{{ currentQuestion.scoreTotal }} 分）
        </div>
      </div>
    </div>
    <div>
      <el-row :gutter="24">
        <el-col :span="18">
          <div class="answer_main" id="title" v-if="titleShow">
            <div class id="printMe" style="padding: 10px" v-loading="loadingTitle">
              <!-- 题目 -->
              <div style="display: flex; justify-content: flex-start">
                <div>{{ currentIndex + 1 }}、</div>
                <!--  v-html="currentQuestion.title" -->
                <div class="answer_main_title" v-html="currentQuestion.title" style="flex: 1"></div>
              </div>
              <!-- 题目的小题 -->
              <div style="padding-left: 50px" v-if="currentQuestion.subQuestions">
                <div style="margin-bottom: 15px" v-for="(subItem, ix) in currentQuestion.subQuestions" :key="ix">
                  <div v-html="ix + 1 + '、' + subItem.title"></div>
                  <div style="margin-top: 20px" v-if="subItem.options&&subItem.options.length">
                    <div v-for="(itemOpt, idx) in subItem.options" :key="idx">
                      <div style="margin-bottom: 15px" v-html="selectOpt[idx] + ' 、 ' + itemOpt"></div>
                    </div>
                  </div>
                </div>
              </div>
              <!-- todo currentQuestion.type == 1 是客观题，2是主观题，3是多选题 type只有1或者2的情况 -->
              <template v-if="currentQuestion.typeId == 1">
                <div style="margin-top: 20px" id="dati">
                  <!-- 遍历客观题的答题项 -->
                  <div v-for="(itemOpt, idx) in currentQuestion.options" :key="idx">
                    <!-- todo 只在state为3和4的时候可以做题 -->
                    <template v-if="
                        (dataDetail.state == 3 ||
                        dataDetail.state == 4 ||
                        dataDetail.state == 7)&& isAnswer

                      ">
                      <!-- 答题 -->
                      <el-radio style="margin-bottom: 15px" v-model="currentQuestion.answer" :label="selectOpt[idx]"
                                border size="medium">
                        {{
                          selectOpt[idx] + ' 、 '
                        }}
                        <span style="white-space: normal" v-html="itemOpt"></span>
                      </el-radio>
                    </template>
                    <template v-else>
                      <!-- 查看 -->
                      <el-radio-group v-model="currentQuestion.answer">
                        <el-radio style="margin-bottom: 15px" :class="{
                          'is-checked' : currentQuestion.answers[0].includes(selectOpt[idx]),
                          'is-error': currentQuestion.answer.includes(selectOpt[idx]) && !currentQuestion.answers[0].includes(selectOpt[idx])
                        }" :label="selectOpt[idx]" disabled border size="medium">
                          {{
                            selectOpt[idx] + ' 、 '
                          }}
                          <span style="white-space: normal" v-html="itemOpt"></span>
                        </el-radio>
                      </el-radio-group>
                    </template>
                  </div>
                </div>
              </template>
              <template v-if="currentQuestion.typeId == 3">
                <div style="margin-top: 20px" id="dati">
                  <!-- 遍历客观题的答题项 -->
                  <div v-for="(itemOpt, idx) in currentQuestion.options" :key="idx">
                    <!-- todo 只在state为3和4的时候可以做题 -->
                    <template v-if="
                        (dataDetail.state == 3 ||
                        dataDetail.state == 4 ||
                        dataDetail.state == 7)&& isAnswer

                      ">
                      <!-- 答题 -->
                      <el-checkbox style="margin-bottom: 15px" v-model="currentQuestion.answer" @change="changeCheckbox"
                                   :label="selectOpt[idx]" border size="medium">
                        {{
                          selectOpt[idx] + ' 、 '
                        }}
                        <span style="white-space: normal" v-html="itemOpt"></span>
                      </el-checkbox>
                    </template>
                    <template v-else>
                      <!-- 查看 -->
                      <el-checkbox-group v-model="currentQuestion.answer">
                        <el-checkbox style="margin-bottom: 15px" :class="{
                          'is-checked' : currentQuestion.answers[0].includes(selectOpt[idx]),
                          'is-error': currentQuestion.answer.includes(selectOpt[idx]) && !currentQuestion.answers[0].includes(selectOpt[idx])
                        }" :label="selectOpt[idx]" disabled border size="medium">
                          {{
                            selectOpt[idx] + ' 、 '
                          }}
                          <span style="white-space: normal" v-html="itemOpt"></span>
                        </el-checkbox>
                      </el-checkbox-group>
                    </template>
                  </div>
                </div>
              </template>
            </div>

            <div>
              <template>
                <div class="answer_main_btn" style="position: relative; display: flex;justify-content: space-between;">
                                    <span v-if="
                      ((dataDetail.state == 3 || dataDetail.state == 4) &&
                        currentQuestion.typeId == 2) ||
                      (dataDetail.state != 3 && dataDetail.state != 4)
                    ">
                                        <el-button v-if="
                        (dataDetail.state == 3 || dataDetail.state == 4) &&
                        currentQuestion.typeId == 2
                      " :type="solvingType == 1 ? 'primary' : ''" @click="answerFunc(1)">手动答题</el-button>
                                        <el-button v-if="
                        (dataDetail.state == 3 || dataDetail.state == 4) &&
                        currentQuestion.typeId == 2
                      " :type="solvingType == 2 ? 'primary' : ''" @click="answerFunc(2)">
                                            <i class="el-icon-camera-solid"></i>拍照上传
                                        </el-button>

                                        <el-button v-if="dataDetail.state != 3 && dataDetail.state != 4"
                                                   :type="solvingType == 3 ? 'primary' : ''"
                                                   @click="answerFunc(3)">解析</el-button>
                                        <el-button v-if="dataDetail.state == 5 &&  currentQuestion.typeId == 2"
                                                   :type="solvingType == 4 ? 'primary' : ''"
                                                   @click="answerFunc(4)">计分</el-button>
                                    </span>
                  <el-button type class="prev_btn" @click="selectSubject('prev')" :disabled="currentIndex == 0">上一题
                  </el-button>
                  <el-button type class="next_btn" @click="selectSubject('next')"
                             :disabled="questionsData.length - 1 == currentIndex">下一题
                  </el-button>
                  <span style="display: inline-block;height: 36px;line-height: 36px;">{{ currentQuestion.type }}</span>
                  <span v-if="dataDetail.state == 5" class="font_color_brown"
                        style="margin: 0;">得分：{{ currentQuestion.score || 0 }}分</span>
                  <div class="question_function_container" style="position: unset;">
                    <div class="question_function_item" @click="$refs.correct.open(currentQuestion.questionId)">
                                            <span class="el-dropdown-link">
                                                <i class="el-icon-warning"></i>
                                                纠错
                                            </span>
                    </div>
                    <div class="question_function_item" @click="downLoad">
                                            <span>
                                                <img v-if="currentQuestion.collect" class="question_function_image"
                                                     src="../../assets/images/shoucang2.png"/>
                                                <img v-else class="question_function_image"
                                                     src="../../assets/images/shoucang.png"/>
                                                收藏
                                            </span>
                    </div>
                  </div>
                </div>
                <div class="upload_container" v-loading="loading" v-if="
                    !(
                      (dataDetail.state == 3 || dataDetail.state == 4) &&
                      currentQuestion.typeId == 1
                    )
                  ">
                  <template v-if="solvingType == 1">
                    <el-input type="textarea" :rows="6" placeholder="请输入内容" v-model="currentQuestion.answer"></el-input>
                  </template>
                  <template v-if="solvingType == 2">
                    <!-- 答题图片展示 -->
                    <ul class="el-upload-list el-upload-list--picture-card" v-if="currentQuestion.typeId == 2">
                      <li tabindex="0" class="el-upload-list__item is-ready el-list-enter-to"
                          v-for="(img, index) in currentQuestion.cacheFiles " :key="index">
                        <img :src="img" alt class="el-upload-list__item-thumbnail"/>
                        <span class="el-upload-list__item-actions">
                                                    <span class="el-upload-list__item-preview"
                                                          @click="handlePictureCardPreview(img)">
                                                        <i class="el-icon-zoom-in"></i>
                                                    </span>
                                                    <span class="el-upload-list__item-delete" @click="deleteImg(index)"
                                                          v-if="
                              dataDetail.state == 3 || dataDetail.state == 4
                            ">
                                                        <i class="el-icon-delete"></i>
                                                    </span>
                                                </span>
                      </li>
                    </ul>
                    <!-- 上传图片 -->
                    <label class="el-upload el-upload--picture-card"
                           v-if="(dataDetail.state == 3 || dataDetail.state == 4) && currentQuestion.typeId == 2">
                      <i class="el-icon-plus"></i>
                      <input type="file" ref="upFile" name="file" accept="image/*" class="el-upload__input"
                             @change="UploadImage"/>
                    </label>
                  </template>
                  <template v-if="solvingType == 3" id="parse">
                    <!-- 解析 -->
                    <el-row :gutter="24">
                      <el-col :span="12">
                        <div>
                          <!--  <div
v-if="dataDetail.state == 5"
  style="padding: 30px"
  v-html="currentQuestion.parse"
                          ></div>-->
                          <div style="padding: 30px"
                               v-if="dataDetail.state == 6 || dataDetail.state == 7||dataDetail.state == 5">
                            <div v-html="'答：' + currentQuestion.answer" style="margin-bottom: 15px;"></div>
                            <div v-if="currentQuestion.typeId == 2">
                              <ul class="el-upload-list el-upload-list--picture-card">
                                <li tabindex="0" class="el-upload-list__item is-ready el-list-enter-to" v-for="(
                                      img, index
                                    ) in currentQuestion.attachments" :key="index">
                                  <img :src="img" alt class="el-upload-list__item-thumbnail"/>
                                  <span class="el-upload-list__item-actions">
                                                                        <span class="el-upload-list__item-preview"
                                                                              @click="handlePictureCardPreview(img)">
                                                                            <i class="el-icon-zoom-in"></i>
                                                                        </span>
                                                                    </span>
                                </li>
                              </ul>
                            </div>
                          </div>
                        </div>
                      </el-col>
                      <el-col :span="12">
                        <div style="padding:30px 30px 0 30px"
                             v-if="(dataDetail.state == 6 || dataDetail.state == 7||dataDetail.state == 5)&& currentQuestion.answers"
                             v-html="'正确答案：'+ currentQuestion.answers[0]"></div>
                        <div v-if="dataDetail.state == 6 || dataDetail.state == 7||dataDetail.state == 5"
                             style="padding:20px 30px 30px 30px" v-html="currentQuestion.parse"></div>
                      </el-col>
                    </el-row>
                  </template>
                  <!-- 记分 -->
                  <template v-if="solvingType == 4">
                    <el-row :gutter="24" id="answer">
                      <el-col :span="12">
                        <div style="padding: 30px">
                          <div v-html="'答：' + currentQuestion.answer" style="margin-bottom: 15px;"></div>
                          <div v-if="currentQuestion.typeId == 2">
                            <ul class="el-upload-list el-upload-list--picture-card">
                              <li tabindex="0" class="el-upload-list__item is-ready el-list-enter-to" v-for="(
                                  img, index
                                ) in currentQuestion.attachments" :key="index">
                                <img :src="img" alt class="el-upload-list__item-thumbnail"/>
                                <span class="el-upload-list__item-actions">
                                                                    <span class="el-upload-list__item-preview"
                                                                          @click="handlePictureCardPreview(img)">
                                                                        <i class="el-icon-zoom-in"></i>
                                                                    </span>
                                                                </span>
                              </li>
                            </ul>
                          </div>
                        </div>
                      </el-col>
                      <el-col :span="12" class="text-center" v-if="
                          dataDetail.state == 5 && currentQuestion.typeId == 2
                        ">
                        <div style="margin-top: 30px">此题总分{{ currentQuestion.scoreTotal }}分</div>
                        <div style="margin-top: 30px">
                          <el-input :disabled="currentQuestion.typeId == 5" class="fenshu" type="number" v-model="score"
                                    min="0" :max="currentQuestion.scoreTotal" placeholder="请输入题目得分" @change="
                              score > currentQuestion.scoreTotal
                                ? (score = currentQuestion.scoreTotal)
                                : (score = Math.floor(score));
                              score < 0
                                ? (score = 0)
                                : (score = Math.floor(score));
                            "></el-input>
                        </div>

                        <el-button :loading="tijiaoLoad" style="
                            margin-top: 30px;
                            margin-bottom: 30px;
                            width: 100px;
                          " type="success" round @click="scoreExamineeQuestion">提交
                        </el-button>
                      </el-col>
                    </el-row>
                  </template>
                  <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt/>
                  </el-dialog>
                </div>
              </template>
              <div class="answer_footer_btn">
                <el-button type v-if="(dataDetail.state == 3 || dataDetail.state == 4)&& isAnswer" class="color_green_a"
                           @click="resetAnswer()">重新做题
                </el-button>
                <el-button type v-if="(dataDetail.state == 3 || dataDetail.state == 4)&& isAnswer" class="color_green_b"
                           @click="selectSubject('next')">完成
                </el-button>
              </div>
              <div class="ft_green" v-if="dataDetail.state == 3 || dataDetail.state == 4">单题计时：{{ subjectTime }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="answer_card">
            <div class="card_title">答题卡</div>
            <div class="card_btn_container">
              <template v-for="(item, index) in questionsData">
                <template v-if="item.typeId == 1 || item.typeId == 3">
                  <button v-if="
                      (item.answer && item.answer.length>0) ||
                      item.cacheFiles.length > 0 ||
                      dataDetail.state > 4
                    " class="btn card_btn color_blue" @click="selectSubject(index)" :key="index">
                    <i v-if="item.score || item.score === 0" class="ebtn_mblem">{{ item.score }}</i>
                    <span style="font-size:16px;font-weight:bold">{{ item.seq }}</span>
                  </button>
                  <button v-else class="btn card_btn color_gblue" @click="selectSubject(index)" :key="index">
                    <span style="font-size:16px;font-weight:bold">{{ item.seq }}</span>
                  </button>
                </template>
                <template v-else>
                  <button v-if="
                      item.answer ||
                      item.cacheFiles.length > 0 ||
                      dataDetail.state > 4
                    " class="btn card_btn color_brown" @click="selectSubject(index)" :key="index">
                    <i v-if="item.score || item.score === 0" class="ebtn_mblem">{{ item.score }}</i>
                    <span style="font-size:16px;font-weight:bold">{{ item.seq }}</span>
                  </button>
                  <button v-else class="btn card_btn color_gbrown" @click="selectSubject(index)" :key="index">
                    <span style="font-size:16px;font-weight:bold">{{ item.seq }}</span>
                  </button>
                </template>
              </template>
            </div>
            <div class="card_timer" v-if="dataDetail.state == 3 || dataDetail.state == 4">
              <span>倒计时：{{ countDown }}</span>
            </div>
            <template v-if="dataDetail.state == 5">
              <div class="text-center" style="margin: 10px 0">
                评测计分：
                <span style="font-size: 28px; font-weight: bold; color: red">{{ jifen() }}</span>
                分
              </div>
            </template>
            <template v-if="dataDetail.state >= 6">
              <div class="text-center" style="margin: 10px 0">
                评测分数：
                <span style="font-size: 28px; font-weight: bold; color: red">{{ jifen() }}</span>
                分
              </div>
            </template>
            <div class="card_footer">
              <template v-if="(dataDetail.state == 3 || dataDetail.state == 4) && isAnswer">
                <el-button type="primary" @click="submitEvaluatingDataSave()">交卷</el-button>
                <el-button>继续做题</el-button>
              </template>
              <template v-if="dataDetail.state == 5">
                <el-button type="primary" @click="closeEvaluating">结束阅卷</el-button>
              </template>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <correct-question ref="correct"></correct-question>
  </div>
</template>

<script>
import {
  openExamineePaper,
  loadExamineePaper,
  competitionQuestions,
  commitExamineePaper,
  commitExamineeQuestion,
  scoreExamineeQuestion,
  teacherScoreExamineeQuestions,
  teacherScoreFinish
} from '@/api/webApi/studentEvaluating'
import {
  uploadGeneratePicAndBindQuestion,
  cancelQuestionCollection
} from '@/api/webApi/front'
import { uploadFile2OSS } from '@/api/webApi/common.js'
import html2canvas from 'html2canvas'
import { formatDuration } from '@/utils/index'
import { mapGetters } from 'vuex'
import correctQuestion from '../../components/MxPaper/plus/correct-question-dialog.vue'

export default {
  components: { correctQuestion },
  data() {
    return {
      loadingTitle: false,
      showcangFla: false,
      submitLoading: false,
      comment: '',
      score: 0,
      loading: true,
      selectOpt: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
      evaluationClassId: null,
      examineeId: null,
      competitionRoundId: null,
      dataDetail: {},
      questionsData: [],
      currentQuestion: {
        answer: ''
      },
      dialogImageUrl: '',
      dialogVisible: false,
      countDown: 0,
      timer: 90 * 60,
      subjectTime: 0,
      solvingType: 2,
      currentIndex: 0, // 当前题目的index
      oldIndex: 0, // 当前题目之前的index
      timeOut: null,
      imgFileList: [],
      imgsrc: '',
      canvasSnswer: '',
      tijiaoLoad: false, //防重复点击
      isAnswer: true,
      canvasAnswers: [],
      radioDisabled: true,
      studentName: '',
      className: '',
      correctTypes: [],
      titleShow: true,
      examineeType: null // examineeType 值为1是测评，值为2是竞赛，进入answer页面必须要的参数
    }
  },
  watch: {
    'currentQuestion.title': function(value) {
      if (value) {
        this.titleShow = false
        this.$nextTick(() => {
          this.titleShow = true
          this.$nextTick(() => {
            this.mxGlobal.MathQueue('title')
          })
        })
      }
    },
    solvingType: function(value) {
      if (value == 3) {
        this.$nextTick(() => this.mxGlobal.MathQueue('parse'))
      }
      if (value == 4) {
        this.$nextTick(() => this.mxGlobal.MathQueue('answer'))
      }
    }
  },
  created() {
    this.evaluationClassId = this.$route.query.evaluationClassId
    this.examineeId = this.$route.query.examineeId
    this.competitionRoundId = this.$route.query.competitionRoundId
    this.studentName = this.$route.query.studentName
    this.className = this.$route.query.className
    // todo 为了方便调试竞赛，只配置了竞赛页面的examineeType，其它需要配置的地方还没有配置，所以设置默认值为1
    this.examineeType = this.$route.query.examineeType || 1
    if (!this.examineeType) {
      this.$message.error('参数非法，请传入正确的参数')
      return
    }
    if (this.isFrontStudent) {
      this.studentName = this.currentUser.nickName
      this.className = this.firstClassName
    }
    this.info()
    this.getCorrectTypes()
  },
  computed: {
    ...mapGetters(['isFrontStudent', 'currentUser', 'firstClassName']),
    userInfo() {
      // TODO: hht 22.1.5 兼容历史写法，待清理
      return this.currentUser
    }
  },
  mounted() {
  },
  destroyed() {
    clearInterval(this.addTimer)
    clearInterval(this.reduceTimer)
  },
  methods: {
    getCorrectTypes() {
      this.getDicts('question_wrong_type').then((res) => {
        this.correctTypes = res.data.map((t) => ({
          label: t.dictLabel,
          value: t.dictValue
        }))
      })
    },
    jifen() {
      let fen = 0
      this.questionsData.forEach((item) => {
        fen += item.score || 0
      })
      return fen
    },
    changeCheckbox(val) {
      let answer = []
      this.selectOpt.forEach((item) => {
        if (this.currentQuestion.answer.indexOf(item) > -1) {
          answer.push(item)
        }
      })
      this.currentQuestion.answer = answer //排序
      console.log(this.currentQuestion.answer)
    },
    //生成图片
    downLoad() {
      var _this = this
      if (this.currentQuestion.collect == true) {
        let Ajax = {
          questionId: this.currentQuestion.questionId,
          examineeType: this.examineeType
        }
        cancelQuestionCollection(Ajax)
          .then((response) => {
            this.currentQuestion.collect = false
            this.$forceUpdate()
          })
          .catch((err) => {
          })
        return
      }

      window.pageYoffset = 0
      document.documentElement.scrollTop = 0
      document.body.scrollTop = 0 //滚动条置顶，解决生成图片不全问题

      this.canvasSnswer = JSON.parse(
        JSON.stringify(this.currentQuestion.answer)
      )
      this.canvasAnswers = JSON.parse(
        JSON.stringify(this.currentQuestion.answers || '')
      )
      this.currentQuestion.answer = ''
      this.currentQuestion.answers = null
      this.radioDisabled = false

      setTimeout(() => {
        let canvas2 = document.createElement('canvas')
        let _canvas = document.getElementById('printMe')
        let w = parseInt(window.getComputedStyle(_canvas).width)
        let h = parseInt(window.getComputedStyle(_canvas).height)
        canvas2.width = w
        canvas2.height = h
        canvas2.style.width = w + 'px'
        canvas2.style.height = h + 'px'
        let context = canvas2.getContext('2d')
        context.scale(1, 1) ///缩放等级
        html2canvas(document.getElementById('printMe'), {
          canvas: canvas2
        }).then(function(canvas) {
          // _this.loadingTitle = true
          _this.submitLoading = true
          let fileName =
            '题目id:' + _this.currentQuestion.questionId + '.jpg'
          let imgUri = canvas.toDataURL('image/jpeg', 2) // 获取生成的图片的url
          _this.imgsrc = imgUri
          console.log(imgUri)
          let title =
            document.getElementsByClassName('answer_main_title')[0]
              .innerText
          var formData = new FormData()
          formData.append('title', title)
          formData.append('base64Data', imgUri)
          formData.append(
            'questionId',
            _this.currentQuestion.questionId
          )
          formData.append('type', 8)
          formData.append('ossType', 7)
          _this.currentQuestion.answer = _this.canvasSnswer
          _this.currentQuestion.answers = _this.canvasAnswers
          _this.radioDisabled = true
          uploadGeneratePicAndBindQuestion(formData)
            .then((response) => {
              _this.currentQuestion.collect = true
              _this.$message.success('收藏成功')
              // _this.loadingTitle = false
              _this.submitLoading = false
            })
            .catch((err) => {
              // _this.loadingTitle = false
              _this.submitLoading = false
            })
        })
      }, 50)
    },

    info() {
      if (this.evaluationClassId) {
        if (this.examineeId) {
          // 老师阅卷获取学生答题详情
          this.getAnswerDataByTeacher()
        } else {
          // 学生答题获取考卷详情
          this.getExamineeQuestions()
        }
      } else if (this.competitionRoundId) {
        // 获取竞赛卷详情
        this.getCompetitionQuestions()
      } else {
        this.$message.error('请选择试卷！')
      }
    },
    // 获取竞赛卷详情
    getCompetitionQuestions() {
      this.loading = true
      openExamineePaper({
        competitionRoundId: this.competitionRoundId,
        examineeType: this.examineeType
      })
        .then((response) => {
          this.detailHandle(response)
        })
        .catch((err) => {
          this.loading = false
        })
    },

    // 老师阅卷获取学生答题详情
    getAnswerDataByTeacher() {
      this.loading = true
      loadExamineePaper({
        evaluationClassId: this.evaluationClassId,
        examineeId: this.examineeId,
        examineeType: this.examineeType
      })
        .then((response) => {
          this.detailHandle(response)
        })
        .catch((err) => {
          this.loading = false
        })
    },

    // 学生考卷详情
    getExamineeQuestions() {
      this.loading = true
      openExamineePaper({
        evaluationClassId: this.evaluationClassId,
        examineeType: this.examineeType
      })
        .then((response) => {
          this.detailHandle(response)
        })
        .catch((err) => {
          this.loading = false
        })
    },

    detailHandle(response) {
      this.dataDetail = response.data
      this.questionsData = [].concat(this.dataDetail.questions)
      this.questionsData.forEach((item, index) => {
        item.answer = item.answer ? item.answer : ''
        item.cacheFiles = item.attachments || []
        item.answerTime = 1
        if (item.typeId == 3) {
          //多选时转成数组
          item.answer = item.answer ? item.answer.split(',') : []
        } else {
          item.answer = item.answer ? item.answer : ''
        }
      })
      //登陆状态是老师且当前是试卷是答题阶段，则老师不可做题
      if (
        this.userInfo &&
        this.userInfo.roles &&
        this.userInfo.roles.length &&
        this.userInfo.roles[0].roleId != 3 &&
        (this.dataDetail.state == 3 || this.dataDetail.state == 4)
      ) {
        this.dataDetail.state = 6
      }
      this.currentQuestion = JSON.parse(
        JSON.stringify(this.questionsData[this.currentIndex])
      )

      if (this.currentQuestion.typeId == 3) {
        //如果是多选，选项改成数组类型
        this.currentQuestion.answer =
          this.currentQuestion.answer.split(',')
      }
      console.log(this.currentQuestion)
      this.timer = this.dataDetail.remaining
      if (
        this.timer > 0 &&
        (this.dataDetail.state == 3 || this.dataDetail.state == 4)
      ) {
        this.timerFunc('reduce')
        this.timerFunc('add')
      } else if (
        this.timer <= 0 &&
        (this.dataDetail.state == 3 || this.dataDetail.state == 4)
      ) {
        this.$message.warning('已超过答题时间')
        // this.$router.go(-1)
        this.isAnswer = false
        this.loading = false
        return
      }
      if (this.dataDetail.state == 3 || this.dataDetail.state == 4) {
        this.solvingType = 1
      } else {
        this.solvingType = 3
      }
      if (this.dataDetail.state == 5) {
        if (this.dataDetail.scoringType == 2 && this.userInfo.roles) {
          let fal = false
          this.userInfo.roles.forEach((item) => {
            if (item.roleKey == 'frontTeacher') {
              fal = true
            }
          })
          if (!fal) {
            this.dataDetail.state = 6
          }
        }
      }
      if (this.dataDetail.state == 5) {
        this.scoreExamineeRadio()
      }
      this.loading = false
    },
    // 答题方式
    answerFunc(type) {
      this.solvingType = type
    },
    checkedAnswers(index) {
      if (
        this.currentQuestion.answer[0].indexOf(this.selectOpt[index]) >
        -1
      ) {
        return 'checked'
      } else {
        return false
      }
    },
    // 重新做题
    resetAnswer() {
      this.currentQuestion.answer = ''
      this.currentQuestion.cacheFiles = []
    },

    // 选择题目
    selectSubject(type) {
      this.showcangFla = false
      let _this = this
      this.imgFileList = []
      this.questionsData[this.currentIndex] = this.currentQuestion
      if (type == 'prev') {
        if (this.currentIndex == 0) {
          this.$message.warning('已经是第一题了')
        } else {
          // this.questionsData[this.currentIndex] = this.currentQuestion
          this.oldIndex = this.currentIndex
          --this.currentIndex
          this.currentQuestion = JSON.parse(
            JSON.stringify(this.questionsData[this.currentIndex])
          )
        }
      } else if (type == 'next') {
        if (this.currentIndex == this.questionsData.length - 1) {
          this.$message.warning('已经是最后一题了')
        } else {
          // this.questionsData[this.currentIndex] = this.currentQuestion
          this.oldIndex = this.currentIndex
          ++this.currentIndex
          this.currentQuestion = JSON.parse(
            JSON.stringify(this.questionsData[this.currentIndex])
          )
        }
      } else {
        // if (type != this.currentIndex) {
        // this.questionsData[this.currentIndex] = this.currentQuestion
        this.oldIndex = this.currentIndex
        this.currentIndex = type
        this.currentQuestion = JSON.parse(
          JSON.stringify(this.questionsData[this.currentIndex])
        )
        // }
      }

      console.log(this.currentQuestion)
      this.score = this.questionsData[this.currentIndex].score
      // 切换后
      if (this.dataDetail.state == 3 || this.dataDetail.state == 4) {
        this.solvingType = 1
      } else {
        this.solvingType = 3
      }
      if (this.isAnswer) {
        clearInterval(this.addTimer)
        this.timerFunc('add')
      }
      if (
        (this.dataDetail.state == 3 || this.dataDetail.state == 4) &&
        this.isAnswer
      ) {
        this.submitEvaluatingData(1)
      }
    },

    // 计时器
    timerFunc: function(type) {
      let that = this
      if (this.dataDetail.state == 3 || this.dataDetail.state == 4) {
        // 启动做题计时
        if ('reduce' == type) {
          // 倒计时
          that.reduceTimer = setInterval(() => {
            if (that.timer > 0) {
              that.countDown = formatDuration(that.timer)
              --that.timer
            } else {
              that.countDown = 0
              clearInterval(that.reduceTimer)
              that.submitEvaluatingData()
            }
          }, 1000)
        } else if ('add' == type) {
          // 计时
          that.subjectTime = 0
          that.addTimer = setInterval(() => {
            that.subjectTime = formatDuration(
              that.currentQuestion.answerTime
            )
            ++that.currentQuestion.answerTime
          }, 1000)
        }
      }
    },

    beforeAvatarUpload(file) {
      let imgType = [
        'image/jpeg',
        'image/JPEG',
        'image/jpg',
        'image/JPG',
        'image/png',
        'image/PNG',
        'image/bmp',
        'image/BMP'
      ]
      const isImg = -1 === imgType.indexOf(file.type) ? false : true
      // const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isImg) {
        this.$message.error('上传文件只能是图片!')
      }
      // if (!isLt5M) {
      //   this.$message.error('上传图片大小不能超过 5MB!');
      // }
      // return isImg && isLt5M;
      return isImg
    },
    deleteImg(index) {
      this.currentQuestion.cacheFiles.splice(index, 1)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file
      this.dialogVisible = true
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    UploadImage(param) {
      if (!this.beforeAvatarUpload(param.target.files[0])) {
        return
      }
      this.loading = true
      const formData = new FormData()
      formData.append('file', param.target.files[0])
      uploadFile2OSS(formData, 6)
        .then((response) => {
          this.currentQuestion.cacheFiles.push(response.msg)
          this.loading = false
        })
        .catch((err) => {
          console.log(err)
          this.loading = false
        })
      this.$refs.upFile.value = ''
    },

    // 保存当前题目的作答信息
    commitExamineeQuestion(param) {
      // todo 从param中获取当前题目的作答，然后保存当前题目的作答信息
      // 根据oldIndex找到param中要保存的数据
      let cacheSave = {}
      cacheSave.examineeId = param.examineeId
      cacheSave.examineeType = param.examineeType
      let questions = param.questions[this.oldIndex]
      if (questions.typeId == 3) {
        //多选时，answer是数组
        questions.answer = questions.answer.join(',')
      }
      cacheSave.questions = [questions]
      commitExamineeQuestion(cacheSave)
        .then((response) => {
          if (response.code == 200) {
            console.log('OK')
            // this.$message.success('交卷成功')
            // this.$router.go(-1)
            // this.loading = false
            // this.submitLoading = false
          }
        })
        .catch((err) => {
          console.log(err)
          // this.submitLoading = false
          // this.loading = false
        })
    },
    submitEvaluatingDataSave() {
      this.questionsData[this.currentIndex] = this.currentQuestion
      let fal = false
      console.log(this.questionsData)
      this.questionsData.forEach((item) => {
        let answer =
          item.answer ||
          (item.cacheFiles && item.cacheFiles.length > 0)
        if (!answer) {
          console.log(item)
          fal = true
        }
      })
      if (fal) {
        this.$confirm('当前试卷未做完，确认要交卷吗?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          closeOnClickModal: false,
          type: 'warning'
        }).then(
          () => {
            this.submitEvaluatingData()
          },
          (error) => {
            this.loading = false
            this.submitLoading = false
            window.console.log(error)
          }
        )
      } else {
        this.submitEvaluatingData()
      }
    },
    // 交卷（提交数据）
    submitEvaluatingData(type) {
      if (!type) {
        this.submitLoading = true
        // 把当前题目的答案缓存到页面数据中
        // this.selectSubject(this.currentIndex)
        this.questionsData[this.currentIndex] = this.currentQuestion
        this.loading = true
      }
      // 封装接口需要的数据结构
      let param = {}
      param.examineeId = this.dataDetail.examineeId
      param.examineeType = this.examineeType
      param.questions = []
      this.questionsData.forEach((item) => {
        let answer = item.answer
        if (item.typeId == 3) {
          //多选时，answer是数组
          answer = item.answer.join(',')
        }
        let cacheObj = {
          questionId: item.questionId,
          answer: answer,
          attachments: item.cacheFiles,
          duration: item.answerTime,
          examineeType: this.examineeType
        }
        param.questions.push(cacheObj)
      })
      console.log(param)
      if (type) {
        // type为1的时候，是切换题目，不要交卷，调commitExamineeQuestion方法保存当前作答
        this.commitExamineeQuestion(param)
      } else {
        commitExamineePaper(param)
          .then((response) => {
            // console.log(response)
            if (!type) {
              this.$message.success('交卷成功')
              this.$router.go(-1)
              this.loading = false
              this.submitLoading = false
            }
          })
          .catch((err) => {
            this.submitLoading = false
            this.loading = false
          })
      }
    },
    //阅卷打分
    scoreExamineeQuestion() {
      let correct = false
      if (
        this.currentQuestion.answers &&
        this.currentQuestion.answers[0] &&
        this.currentQuestion.answer == this.currentQuestion.answers[0]
      ) {
        correct = true
      }
      let param = {
        examineeId: this.dataDetail.examineeId,
        examineeType: this.examineeType
      }
      this.currentQuestion.score = this.score || 0
      let list = [
        {
          score: this.currentQuestion.score,
          questionId: this.currentQuestion.questionId,
          examineeType: this.examineeType
        }
      ]
      this.tijiaoLoad = true
      param.questions = list
      if (this.evaluationClassId) {
        if (this.examineeId) {
          //老师打分
          teacherScoreExamineeQuestions(param)
            .then((response) => {
              this.tijiaoLoad = false
              this.$message.success(response.msg)
              this.selectSubject('next')
            })
            .catch((err) => {
              this.tijiaoLoad = false
              this.$message.error(err.msg)
            })
        } else {
          //学生
          scoreExamineeQuestion(param)
            .then((response) => {
              this.tijiaoLoad = false
              this.$message.success(response.msg)
              this.selectSubject('next')
            })
            .catch((err) => {
              this.tijiaoLoad = false
              this.$message.error(err.msg)
            })
        }
      } else {
        this.$message.error('参数异常！')
      }
    },
    //批量阅卷打分
    scoreExamineeRadio() {
      let list = []
      let param = {
        examineeId: this.dataDetail.examineeId,
        examineeType: this.examineeType
      }
      this.questionsData.forEach((item) => {
        let correct = 0
        if (item.typeId == 1 && !item.score && item.score !== 0) {
          //单选
          if (
            item.answers &&
            item.answers[0] &&
            item.answer == item.answers[0]
          ) {
            correct = item.scoreTotal
          }
          list.push({
            score: correct,
            // examineeId: this.dataDetail.examineeId,
            questionId: item.questionId,
            examineeType: this.examineeType
          })
        } else if (
          item.typeId == 3 &&
          !item.score &&
          item.score !== 0
        ) {
          //多选
          let correct = 0
          if (
            item.answers &&
            item.answers[0] &&
            item.answer.join(',') == item.answers[0]
          ) {
            correct = item.scoreTotal
          }
          list.push({
            score: correct,
            questionId: item.questionId,
            examineeType: this.examineeType
          })
        }
      })
      if (list.length > 0) {
        param.questions = list
        if (this.evaluationClassId) {
          if (this.examineeId) {
            //打分老师
            teacherScoreExamineeQuestions(param)
              .then((response) => {
                if (response.code == 200) {
                  this.questionsData.forEach(
                    (item, index) => {
                      if (
                        item.typeId == 1 &&
                        !item.score &&
                        item.score !== 0
                      ) {
                        let correct = 0
                        if (
                          item.answers &&
                          item.answers[0] &&
                          item.answer ==
                          item.answers[0]
                        ) {
                          correct = item.scoreTotal
                        }
                        item.score = correct
                        if (
                          index == this.currentIndex
                        ) {
                          //给当前题目赋值分数
                          this.currentQuestion.score =
                            correct
                        }
                      } else if (
                        item.typeId == 3 &&
                        !item.score &&
                        item.score !== 0
                      ) {
                        //多选
                        let correct = 0
                        if (
                          item.answers &&
                          item.answers[0] &&
                          item.answer.join(',') ==
                          item.answers[0]
                        ) {
                          correct = item.scoreTotal
                        }
                        item.score = correct
                        if (
                          index == this.currentIndex
                        ) {
                          //给当前题目赋值分数
                          this.currentQuestion.score =
                            correct
                        }
                      }
                    }
                  )
                  this.$forceUpdate()
                }
              })
              .catch((err) => {
              })
          } else {
            scoreExamineeQuestion(param)
              .then((response) => {
                if (response.code == 200) {
                  this.questionsData.forEach(
                    (item, index) => {
                      if (
                        item.typeId == 1 &&
                        !item.score &&
                        item.score !== 0
                      ) {
                        let correct = 0
                        if (
                          item.answers &&
                          item.answers[0] &&
                          item.answer ==
                          item.answers[0]
                        ) {
                          correct = item.scoreTotal
                        }
                        item.score = correct
                        if (
                          index == this.currentIndex
                        ) {
                          //给当前题目赋值分数
                          this.currentQuestion.score =
                            correct
                        }
                      } else if (
                        item.typeId == 3 &&
                        !item.score &&
                        item.score !== 0
                      ) {
                        //多选
                        let correct = 0
                        if (
                          item.answers &&
                          item.answers[0] &&
                          item.answer.join(',') ==
                          item.answers[0]
                        ) {
                          correct = item.scoreTotal
                        }
                        item.score = correct
                        if (
                          index == this.currentIndex
                        ) {
                          //给当前题目赋值分数
                          this.currentQuestion.score =
                            correct
                        }
                      }
                    }
                  )
                  this.$forceUpdate()
                }
              })
              .catch((err) => {
              })
          }
        }
      }
    },

    // 结束阅卷
    closeEvaluating() {
      this.selectSubject(this.currentIndex)

      try {
        let fal = true
        this.questionsData.forEach((item, index) => {
          if (item.score >= 0) {
          } else {
            fal = false
          }
        })
        if (fal) {
          this.commitEvaluating()
        } else {
          this.$message.warning('还未批阅完，不能结束阅卷')
        }
      } catch (e) {
        console.log(e)
      }
    },

    commitEvaluating() {
      this.submitLoading = true
      let that = this
      teacherScoreFinish({
        examineeId: that.dataDetail.examineeId,
        examineeType: this.examineeType
      })
        .then((response) => {
          this.submitLoading = false
          this.$message.success(response.msg)
          this.$router.go(-1)
        })
        .catch((err) => {
          this.submitLoading = false
          this.$message.error(err.msg)
        })
    }
  }
}
</script>

<style>
.upload_container img {
  max-width: 100%;
}
</style>
<style lang="scss" scoped>
.btn {
  background-color: #ffffff;
  border: 1px solid #dcdfe6;
  color: #606266;
  display: inline-block;
  cursor: pointer;
}

.font_color_brown {
  color: #d77616;
  font-size: 20px;
  margin-left: 10%;
}

.color_gblue {
  background-color: #cfdcd5;
  color: #ffffff;
}

.color_blue {
  background-color: #47c6a2;
  color: #ffffff;
}

.color_brown {
  background-color: #f77e67;
  color: #ffffff;
}

.color_gbrown {
  background-color: #fbd0a6;
  color: #ffffff;
}

.color_gray {
  background-color: #ffcbc1;
  color: #ffffff;
}

.answer_title {
  text-align: center;
  position: relative;

  img {
    width: 50px;
    height: 50px;
  }

  .answer_title_info {
    position: absolute;
    left: 10px;
    top: 10px;
    text-align: left;

    span {
      margin-right: 10px;
    }
  }

  .answer_title_name {
    font-size: 32px;
    font-weight: 500;
    margin: 5px 0 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #dbdbdb;
  }
}

.answer_main {
  .answer_main_title {
    margin-bottom: 30px;
    word-break: break-all;

    img {
      max-width: 100%;
    }
  }

  .answer_main_btn {
    margin: 10px 0;

    button {
      // margin-left: 20px;
    }

    .question_function_container {
      position: absolute;
      top: 0;
      right: 0;
      text-align: right;
      display: flex;

      .question_function_item {
        margin-left: 20px;
        padding: 5px 0;
        cursor: pointer;
        display: flex;

        span {
          display: flex;
          justify-content: center;
          align-items: center;
        }

        i,
        img {
          margin-right: 5px;
        }

        .question_function_image {
          width: 24px;
          font-size: 24px;
          color: orange;
        }
      }
    }
  }

  .upload_container {
    border: 1px solid #6cd1b5;
    padding: 10px;
    border-radius: 8px;
    min-height: 200px;
  }

  .answer_footer_btn {
    display: flex;
    justify-content: space-between;
    margin: 15px 0 30px;

    .color_green_a {
      border: 1px solid #6cd1b5;
      color: #6cd1b5;
    }

    .prev_btn {
      padding: 0;
      border: 1px solid #dcdfe6;
      border-radius: 50%;
      color: #333;
      width: 35px;
      height: 35px;
      line-height: 35px;
      text-align: center;
    }

    .next_btn {
      padding: 0;
      border: 1px solid #dcdfe6;
      border-radius: 50%;
      color: #333;
      width: 35px;
      height: 35px;
      line-height: 35px;
      text-align: center;
    }

    .color_green_b {
      border: 1px solid #6cd1b5;
      background-color: #6cd1b5;
      color: #ffffff;
    }
  }

  .ft_green {
    color: #6cd1b5;
    margin: 30px 0;
  }
}

.answer_card {
  border: 1px solid #dcdfe6;
  padding-bottom: 15px;

  .card_title {
    text-align: center;
    font-size: 20px;
    padding: 15px;
  }

  .card_btn_container {
    padding: 15px 0 15px 15px;

    .card_btn {
      position: relative;
      padding: 0;
      width: 40px;
      height: 40px;
      border-radius: 50%;
      text-align: center;
      margin-right: 15px;
      margin-bottom: 15px;

      .ebtn_mblem {
        position: absolute;
        top: -5px;
        right: -5px;
        width: 20px;
        height: 20px;
        line-height: 20px;
        text-align: center;
        font-size: 14px;
        background-color: red;
        color: #ffffff;
        border-radius: 50%;
      }
    }
  }

  .card_timer {
    padding: 25px;
    text-align: center;
    color: #fd0303;
  }

  .card_footer {
    display: flex;
    justify-content: space-around;
  }
}
</style>
<style scoped>
.el-checkbox.is-bordered.is-checked,
.el-radio.is-bordered.is-checked {
  border-color: #47c6a2;
}

.el-checkbox.is-bordered.is-error,
.el-radio.is-bordered.is-error {
  border-color: #f56c6c !important;
}

/deep/ .el-radio__input.is-checked .el-radio__inner {
  border-color: #47c6a2;
  background: #47c6a2;
}

.el-radio.is-bordered.is-checked /deep/ .el-radio__label {
  color: #47c6a2;
}

.el-radio.is-bordered.is-error /deep/ .el-radio__label {
  color: #f56c6c !important;
}

.fenshu /deep/ .el-input__inner {
  width: 50%;
  line-height: 40px;
  border: none;
  background: #eee;
  color: #333;
  text-align: center;
}

.el-radio--medium.is-bordered {
  height: auto;
  padding-bottom: 8px;
}

.fenshu:focus-visible {
  outline: none;
}

/deep/ .el-textarea__inner {
  height: 180px;
}

/deep/ .el-dropdown-link {
  cursor: pointer;
  font-size: 16px;
  color: #333333;
}

/deep/ .el-icon-warning {
  font-size: 24px;
  color: #999999;
}

.el-checkbox.is-bordered.el-checkbox--medium {
  height: auto;
}
</style>
