<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧答题卡 -->
      <el-col :span="6" :offset="0">
        <el-card class="box-card">
          <div class="top-content">
            <div class="title">答题卡</div>
          </div>
          <el-divider></el-divider>

          <el-row :gutter="10" class="mb8">
            <el-col :span="8">
              <div class="color-box" style="background-color: #67c23a"></div>
              <span>已答</span>
            </el-col>
            <el-col :span="8">
              <div class="color-box" style="background-color: #909399"></div>
              <span>未答</span>
            </el-col>
          </el-row>
          <!-- 单选题 -->
          <el-row :gutter="10" class="mb8">
            <div style="margin: 5px">单选题</div>
            <el-col
              :span="4.8"
              v-for="(item, index) in questionList.filter(item => item.questionType == 1)"
              :key="index"
            >
              <div style="margin-bottom: 5px; cursor: pointer" @click="currentIndex = item.questionIndex - 1">
                <el-tag v-if="item.questionIndex == currentIndex + 1">{{ item.questionIndex }}</el-tag>
                <el-tag v-else-if="item.isPass" type="success">{{ item.questionIndex }}</el-tag>
                <el-tag v-else-if="item.isNotAnswer" type="info">{{ item.questionIndex }}</el-tag>
              </div>
            </el-col>
          </el-row>
          <!-- 多选题 -->
          <el-row :gutter="10" class="mb8">
            <div style="margin: 5px">多选题</div>
            <el-col
              :span="4.8"
              v-for="(item, index) in questionList.filter(item => item.questionType == 2)"
              :key="index"
            >
              <div style="margin-bottom: 5px; cursor: pointer" @click="currentIndex = item.questionIndex - 1">
                <el-tag v-if="item.questionIndex == currentIndex + 1">{{ item.questionIndex }}</el-tag>
                <el-tag v-else-if="item.isPass" type="success">{{ item.questionIndex }}</el-tag>
                <el-tag v-else-if="item.isNotAnswer" type="info">{{ item.questionIndex }}</el-tag>
              </div>
            </el-col>
          </el-row>
          <!-- 判断题 -->
          <el-row :gutter="10" class="mb8">
            <div style="margin: 5px">判断题</div>
            <el-col
              :span="4.8"
              v-for="(item, index) in questionList.filter(item => item.questionType == 3)"
              :key="index"
            >
              <div style="margin-bottom: 5px; cursor: pointer" @click="currentIndex = item.questionIndex - 1">
                <el-tag v-if="item.questionIndex == currentIndex + 1">{{ item.questionIndex }}</el-tag>
                <el-tag v-else-if="item.isPass" type="success">{{ item.questionIndex }}</el-tag>
                <el-tag v-else-if="item.isNotAnswer" type="info">{{ item.questionIndex }}</el-tag>
              </div>
            </el-col>
          </el-row>
          <!-- 简答题 -->
          <!-- <el-row :gutter="10" class="mb8">
            <div style="margin: 5px">简答题</div>
            <el-col :span="4.8" v-for="(item, index) in shortAnswerTopic" :key="index">
              <div style="margin-bottom: 5px">
                <el-tag v-if="item.isPass" type="success">{{ item.item.questionIndex }}</el-tag>
                <el-tag v-if="item.isError" type="danger">{{ item.item.questionIndex }}</el-tag>
                <el-tag v-if="item.isNotAnswer" type="info">{{ item.item.questionIndex }}</el-tag>
              </div>
            </el-col>
          </el-row> -->
        </el-card>
      </el-col>
      <!-- 右侧试卷详情 -->
      <el-col :span="18" :offset="0">
        <el-card class="box-card">
          <div class="top-content">
            <div class="title">{{ opt.name || opt.fileName }}</div>
            <div style="margin-left: 50px">计时器: {{ timeCount }}</div>
          </div>
          <div style="margin-left: 10px">共{{ questionList.length }}道练习题</div>
        </el-card>
        <!-- 题目 -->
        <el-card class="box-card">
          <div class="question-wrapper">
            <div
              class="question-list"
              v-for="(item, index) in questionList"
              :key="item.id"
              v-show="index == currentIndex"
            >
              <div class="question-type">
                <div class="line"></div>
                <div class="type">
                  <div v-if="item.questionType == 1">单选题({{ opt.singleScore }})分</div>
                  <div v-else-if="item.questionType == 2">多选题({{ opt.multipleScore }})分</div>
                  <div v-else-if="item.questionType == 3">判断题({{ opt.judgeScore }})分</div>
                </div>
              </div>
              <div class="question-title">{{ index + 1 }}. {{ item.content }}</div>
              <div class="question-img-list">
                <div class="img" v-for="(img, imgIndex) in item.questionPictureVoList">
                  <el-image
                    :key="imgIndex"
                    :src="img.url"
                    :showLoading="true"
                    width="60px"
                    height="60px"
                    :preview-src-list="[img.url]"
                  />
                </div>
              </div>
              <div class="question-item">
                <div v-if="item.questionType == 1 || item.questionType == 3">
                  <!-- 单选题 -->
                  <el-radio-group v-model="item.radioValue">
                    <el-radio
                      :customStyle="{ marginBottom: '8px' }"
                      v-for="(question, index) in item.questionAnswerVoList"
                      :key="index"
                      :label="question.options + '. ' + question.answerOptions"
                      :name="question.options + '. ' + question.answerOptions"
                      :disabled="question.disabled"
                      @change="radioChange(item, question)"
                    >
                      <div class="radio-item">
                        <div class="radio-name">{{ question.options + '. ' + question.answerOptions }}</div>
                        <div class="question-img-list">
                          <div class="img" v-for="(img, imgIndex) in question.questionPictureVoList">
                            <el-image
                              :key="imgIndex"
                              :src="img.url"
                              :showLoading="true"
                              width="60px"
                              height="60px"
                              :preview-src-list="[img.url]"
                            />
                          </div>
                        </div>
                      </div>
                    </el-radio>
                  </el-radio-group>
                </div>

                <div v-if="item.questionType == 2">
                  <!-- 多选题 -->
                  <el-checkbox-group v-model="item.checkboxValue">
                    <div v-for="(question, index) in item.questionAnswerVoList">
                      <el-checkbox
                        :customStyle="{ marginBottom: '8px' }"
                        :key="index"
                        :label="question.options + '. ' + question.answerOptions"
                        :name="question.options + '. ' + question.answerOptions"
                        :disabled="question.disabled"
                        @change="radioChange(item, question)"
                      ></el-checkbox>
                      <div class="radio-item">
                        <div class="question-img-list" style="margin: 10px">
                          <div class="img" v-for="(img, imgIndex) in question.questionPictureVoList">
                            <el-image
                              :key="imgIndex"
                              :src="img.url"
                              :showLoading="true"
                              width="60px"
                              height="60px"
                              :preview-src-list="[img.url]"
                            />
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-checkbox-group>
                </div>

                <!-- 标签 -->
                <div class="tag-list">
                  <el-tag :key="tag.id" v-for="(tag, tagIndex) in item.tagList" style="margin-right: 10px">
                    {{ tag.name }}
                  </el-tag>
                </div>
              </div>
            </div>
          </div>

          <!-- 按钮 -->
          <div class="bottom-wrapper">
            <el-button
              class="btn"
              type="primary"
              size="small"
              shape="circle"
              @click="currentIndex--"
              :disabled="currentIndex == 0"
            >
              上一题
            </el-button>
            <el-button
              class="btn"
              type="primary"
              size="small"
              shape="circle"
              @click="currentIndex++"
              :disabled="currentIndex == questionList.length - 1"
            >
              下一题
            </el-button>
            <el-button class="btn" type="primary" size="small" shape="circle" @click="handleDialogVisible">
              交 卷
            </el-button>
          </div>
        </el-card>
        <div class="box"></div>
      </el-col>
    </el-row>

    <el-dialog title="操作确认" :visible.sync="dialogVisible" width="30%">
      <span style="margin-left: 15px; font-weight: 800; font-size: 16px">
        {{ isNotAnswer > 0 ? '你还有' + isNotAnswer + '题未答, 是否确定交卷' : '确定交卷吗?' }}
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" v-loading.fullscreen.lock="fullscreenLoading" @click="handleSubmit" v-preventReClick="5000">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { lookFile } from '@/utils/bonus'
import { getWebExamQuestion, getWebQuestion, webSubmitAnswer, updateQuestionAnswer } from '@/api/educTrainLearn'

export default {
  data() {
    return {
      fullscreenLoading: false,
      dialogVisible: false,
      currentIndex: 0,
      score: 0, // 总分数
      correctNum: 0, // 正确题数
      errorNum: 0, // 错误题数
      timer: null, // 计时器
      time: 0, // 时间
      timeCount: '00:00:00', // 时间 00:00:00
      answerTime: 0, // 答题时间
      opt: {
        isStudyTask: false, // 是否是学习任务考试
        singleScore: 0, // 单选题分数
        multipleScore: 0, // 多选题分数
        judgeScore: 0, // 判断题分数
      },
      // 题目列表
      questionList: [],
      isNotAnswer: 0, // 未答题数
    }
  },
  created() {
    console.log('🚀 ~ created ~ this.opt:', this.$route.query)
    this.opt = this.$route.query
    if (this.opt.isStudyTask == 'true') {
      this.opt.isStudyTask = true
    } else {
      this.opt.isStudyTask = false
    }
    this.getQuestionList()
  },
  methods: {
    // 获取题目列表
    async getQuestionList() {
      try {
        console.log(this.opt)
        let res = {}
        if (this.opt.isStudyTask) {
          res = await getWebQuestion({ examId: this.opt.id })
          this.questionList = res.data
        } else {
          const params = {
            examPaperId: this.opt.examPaperId,
            practiceType: 3,
          }
          res = await getWebExamQuestion(params)
          this.questionList = res.data.data
        }
        console.log('🚀 ~ getQuestionList ~ 考试题目:', res)
        this.time = Number(this.opt.examTime) * 60
        this.questionList.forEach((item, index) => {
          item.questionIndex = this.$set(item, 'questionIndex', index + 1)
          item.isPass = false
          item.isNotAnswer = true
          if (item.questionPictureVoList && item.questionPictureVoList.length > 0) {
            item.questionPictureVoList.forEach(img => {
              img.url = lookFile() + img.pictureUrl.replace(/\\/g, '/')
            })
          }
          if (item.questionAnswerVoList && item.questionAnswerVoList.length > 0) {
            // 添加一个 radiovalue 字段，用于记录用户选择的答案
            if (item.questionType == 1 || item.questionType == 3) {
              item.radioValue = ''
            } else if (item.questionType == 2) {
              item.checkboxValue = this.$set(item, 'checkboxValue', [])
            }
            item.chooseAnswer = ''
            item.questionAnswerVoList.forEach(answer => {
              if (answer.questionPictureVoList && answer.questionPictureVoList.length > 0) {
                // 图片路径拼接
                answer.questionPictureVoList.forEach(opt => {
                  opt.url = lookFile() + opt.pictureUrl.replace(/\\/g, '/')
                })
              }
            })
          }
        })
        console.log('🚀 ~ getQuestionList ~ this.题目列表:', this.questionList)
        this.startTimer()
      } catch (error) {
        console.log('🚀 ~ getQuestionList ~ error:', error)
      }
    },
    // 开启计时器
    startTimer() {
      this.timer = setInterval(() => {
        this.time--
        this.answerTime++
        if (this.time <= 0) {
          clearInterval(this.timer)
          // 提示
          this.$message({
            message: '考试时间到，系统将自动交卷',
            type: 'warning',
          })
          setTimeout(() => {
            this.handleSubmit()
          }, 500)
        }
        // 时间格式 00:00:00
        const hour = Math.floor(this.time / 3600)
        const minute = Math.floor((this.time % 3600) / 60)
        const second = this.time % 60
        this.timeCount = `${hour < 10 ? '0' + hour : hour}:${minute < 10 ? '0' + minute : minute}:${
          second < 10 ? '0' + second : second
        }`
      }, 1000)
    },
    radioChange(item, question) {
      console.log('🚀 ~ radioChange ~ item:', item)
      console.log('🚀 ~ radioChange ~ question:', question)
      this.handleOption(item)
    },
    // 选择选项
    handleOption(item) {
      console.log('🚀 ~ handleOption ~ item:', item)
      if (item.questionType == 1 || item.questionType == 3) {
        item.chooseAnswer = String(item.radioValue.split('')[0].charCodeAt() - 65)
        // item.correctAnswer1 = String.fromCharCode(65 + Number(item.correctAnswer))
        // item.chooseAnswer1 = String.fromCharCode(65 + Number(item.chooseAnswer))
        item.isPass = true
        item.isNotAnswer = false
      } else if (item.questionType == 2) {
        if (item.checkboxValue.length == 0) {
          item.isNotAnswer = true
          item.isPass = false
          item.chooseAnswer = ''
          // item.chooseAnswer1 = ''
          // item.correctAnswer1 = ''
          return
        } else {
          item.isPass = true
          item.isNotAnswer = false
          let chooseAnswer = item.checkboxValue.map(item => item.split('')[0].charCodeAt() - 65)
          chooseAnswer.sort((a, b) => a - b)
          item.chooseAnswer = chooseAnswer.join(',')
          console.log('🚀 ~ handleOption ~ item.chooseAnswer:', item.chooseAnswer)
        }
      }
    },
    handleDialogVisible() {
      this.isNotAnswer = 0
      this.questionList.forEach(item => {
        if (!item.chooseAnswer) {
          this.isNotAnswer += 1
        }
      })
      this.dialogVisible = true
    },
    async handleSubmit() {
      try {
        this.fullscreenLoading = true
        clearInterval(this.timer)
        console.log('🚀 ~ handleSubmit ~ this.timeCount:', this.timeCount)
        // 计算总分
        this.questionList.forEach(item => {
          item.selectAnswer = item.chooseAnswer
          if (item.chooseAnswer == item.correctAnswer) {
            this.correctNum++
            if (item.questionType == 1) {
              item.scorePerQuestion = Number(this.opt.singleScore)
              this.score += Number(this.opt.singleScore)
            } else if (item.questionType == 2) {
              item.scorePerQuestion = Number(this.opt.multipleScore)
              this.score += Number(this.opt.multipleScore)
            } else if (item.questionType == 3) {
              item.scorePerQuestion = Number(this.opt.judgeScore)
              this.score += Number(this.opt.judgeScore)
            }
            this.score += item.score
          } else {
            item.scorePerQuestion = 0
            this.errorNum++
          }
        })

        let scoringRete = 0
        scoringRete = ((this.correctNum / (this.correctNum + this.errorNum)) * 100).toFixed(2)
        if (scoringRete == 'NaN' || scoringRete == 'Infinity' || scoringRete == '0.00') {
          scoringRete = 0
        }

        const params = {
          userId: this.opt.userId,
          taskId: this.opt.taskId,
          type: this.opt.type,
          examPaperId: this.opt.examPaperId,
          id: this.opt.examPaperId,
          score: this.score,
          answerTime: this.answerTime,
          answerList: this.questionList,
          scoringRete: scoringRete,
          scoreRate: scoringRete,
          selectAnswerList: this.questionList,
        }
        console.log('🚀 ~ handleSubmit ~ params:', params)
        let res = {}
        if (this.opt.isStudyTask) {
          const res = await updateQuestionAnswer(params)
          console.log('🚀 ~ openDialog2 ~ 提交:', res)
        } else {
          res = await webSubmitAnswer(params)
        }
        console.log('🚀 ~ handleSubmit ~ 提交:', res)
        this.dialogVisible = false
        this.fullscreenLoading = false
        // 关闭页面
        this.$tab.closePage().then(() => {
          // 关闭成功
          console.log('关闭成功')
          this.$router.replace({
            path: '/educTrainLearn/examTask/examDetails',
            query: {
              examPaperId: this.opt.examPaperId,
              userId: this.$store.state.user.id,
              type: this.opt.isStudyTask ? 1 : '',
              isStudyTask: this.opt.isTrainTask ? !this.opt.isStudyTask : this.opt.isStudyTask,
            },
          })
        })
      } catch (error) {
        console.log('🚀 ~ handleSubmit ~ error:', error)
        this.fullscreenLoading = false
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.box-card {
  margin-bottom: 20px;
}

.top-content {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 10px;

  .title {
    font-size: 16px;
    font-weight: bold;
  }

  .lf-line {
    width: 2px;
    height: 20px;
    background-color: #ccc;
    margin: 0 20px;
  }
}

.tab-wrapper {
  display: flex;
  justify-content: flex-start;
  padding: 10px;
  margin-bottom: 20px;

  .item {
    cursor: pointer;
    padding: 5px 10px;
    border-radius: 5px;
    border: 1px solid #409eff;
    margin-right: 10px;

    &.active {
      background-color: #409eff;
      color: #fff;
    }
  }
}

.color-box {
  width: 10px;
  height: 10px;
  display: inline-block;
  margin-right: 5px;
}

.top-item {
  color: #409eff;
}

.question-wrapper {
  margin-top: 30px;
  .question-type {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .line {
      width: 3px;
      height: 15px;
      background-color: #1989fa;
    }
    .type {
      padding: 0 10px;
    }
  }
  .question-title {
    margin: 10px 0;
    font-size: 15px;
    font-weight: 800;
    color: #333;
  }
  .question-img-list {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    margin-top: 10px;
  }
  .img {
    margin-right: 10px;
    width: 60px;
    height: 60px;
    overflow: hidden;
  }
  .radio-item {
    margin-left: 10px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    .radio-name {
      margin-bottom: 5px;
    }
  }
  .question-item {
    margin-top: 20px;
  }
  .answer-wrap {
    margin-top: 20px;
    display: flex;
    justify-content: space-around;
    background-color: #edf2f7;
    border-radius: 8px;
    padding: 10px;
    .answer-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      div {
        margin-bottom: 5px;
      }
    }
    .answer-line {
      width: 1px;
      height: 45px;
      background-color: #ccc;
    }
  }
  .analysis {
    padding: 10px;
    background-color: #f5f5f5;
    border-radius: 8px;
    min-height: 100px;
  }
}
.el-radio-group {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.el-radio {
  display: flex;
  margin-bottom: 10px;
}
.box {
  height: 5vh;
}
.bottom-wrapper {
  width: 100vw;
  position: fixed;
  bottom: 0;
  right: 0;
  padding: 10px;
  background-color: #fff;
  display: flex;
  justify-content: center;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  .btn {
    margin: 0 15px;
  }
}
.exercise-result {
  display: flex;
  flex-direction: column;
  justify-self: center;
  align-items: center;
  .top-content {
    font-size: 18px;
    font-weight: 800;
  }
  .content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 100%;
    margin-top: 20px;
  }
  .bt-content {
    display: flex;
    align-items: center;
    width: 100%;
    margin-top: 20px;
    .content-item {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      margin: 10px;
    }
    & > :nth-child(2) {
      margin: 0 39px;
    }
  }
}
</style>
