<template>
  <a-modal
    title="课中检查"
    :visible="visible"
    :confirm-loading="confirmLoading"
    :footer="null"
    :closable="false"
  >
    <DbQuestionItem :data="data"></DbQuestionItem>
    <div class="text-center margin-top">
      <a-button type="primary" @click="handlerSubmit">提交</a-button>
    </div>
    <p class="tip-info margin-top">
      注意：每段课程学习完成后都会随机出现1道小题，答对题目，方可继续下一部分学习，您有{{
        chance
      }}次机会。否则之前上一小段学习时间不计算学时，需要重新学习
    </p>
  </a-modal>
</template>

<script>
import DbQuestionItem from '@/components/DbQuestionItem/index.vue'
import { reqCourseExam } from '@/api/mycourse/index.js'
export default {
  components: { DbQuestionItem },
  props: {
    curVideo: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      visible: false,
      confirmLoading: false,
      chance: 2, // 初始机会2次
      data: {} // 题目信息
    }
  },
  methods: {
    show () {
      this.chance = 2
      this.visible = true
    },
    // 获取课中题目
    getExamQuestion () {
      const curVideo = this.curVideo
      const query = this.$route.query
      const { person } = this.$store.state.user
      const params = {
        courseId: curVideo.courseId,
        coursewareId: curVideo.id,
        personId: person.id,
        projectId: query.courseId,
        count: ''
      }
      reqCourseExam(params).then(res => {
        this.data = res.data
      })
    },
    handlerSubmit () {
      // 处理考试提交逻辑
      const curVideo = this.curVideo
      const { person } = this.$store.state.user
      const query = this.$route.query
      const question = { ...this.data }
      if (Array.isArray(question.myAnswers)) {
        question.myAnswerList = question.myAnswers
        question.myAnswers = question.myAnswers && question.myAnswers.join(',')
      } else {
        question.myAnswerList = question.myAnswers && question.myAnswers.split(',')
      }
      const params = {
        courseId: curVideo.courseId,
        coursewareId: curVideo.id,
        personId: person.id,
        projectId: query.courseId,
        count: ''
      }
      reqCourseExam(params, question).then(res => {
        // this.data = res.data
        const data = res.data
        if (res.correctness) {
          this.$message.success('恭喜你,回答正确!')
          this.visible = false
        } else {
          if (this.chance === 1) {
            this.visible = false
          } else {
            this.data = data
          }
          this.$message.warning('很遗憾,回答错误!')
          this.chance--
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.tip-info {
  margin-top: 10px;
  color: #f5222d;
}
</style>
