<template>
  <container :title="detail.title" v-loading="loading">
    <div class="exam">
      <template v-if="status.examination_status === '00'">
        <div class="no-exam">暂无考试</div>
      </template>
      <template v-else-if="isSubmited && !isExamComplete">
        <div class="no-exam">试卷批改中，请耐心等待</div>
      </template>
      <template v-else>
        <!-- 考试期间，未开始考试 -->
        <div class="exam-welcome" v-if="!isStartExam">
          <div>考试时间：{{status.start_time}} ~ {{status.terminate_time}}</div>
          <el-button
            type="primary"
            :disabled="!isExamTime"
            @click="onStartExam"
          >{{startExamButtonText}}</el-button>
        </div>
        <!-- 考试完成 -->
        <div class="exam-finish" v-if="isExamComplete">
          <table class="exam-table">
            <tr>
              <th>单选</th>
              <th>多选</th>
              <th>简答</th>
            </tr>
            <tr>
              <td>{{exam.score.radio}}分</td>
              <td>{{exam.score.checkbox}}分</td>
              <td>{{exam.score.shortAnswer}}分</td>
            </tr>
            <tr>
              <td colspan="3">
                <div class="exam-total">总分：{{exam.score.total}}分</div>
              </td>
            </tr>
          </table>
          <el-button type="text" @click="examVisible = !examVisible">查看试卷</el-button>
        </div>
        <!-- 考试试题 -->
        <div class="exam-form" v-if="isStartExam" v-show="examVisible">
          <el-form :disabled="isSubmited">
            <exam-item
              v-for="(item, index) in questions"
              :index="index"
              :type="item.type"
              :data="item"
              :value="item.formModel"
              :disabled="isSubmited"
              :key="item.id"
            ></exam-item>
            <div class="exam-buttons">
              <el-tooltip effect="dark" content="提交之后就不能修改了哦" placement="right">
                <el-button type="primary" @click="onSubmit">{{submitText}}</el-button>
              </el-tooltip>
            </div>
          </el-form>
        </div>
      </template>
    </div>
  </container>
</template>

<script>
import Base64 from 'Base64'

// components
import Container from '../common/container.vue'
import ExamItem from './examItem.vue'
// api
import * as api from '../../api'

// 章节测试题
export default {
  name: 'CourseExam',
  components: { Container, ExamItem },
  props: {
    // 当前选中的章节
    chapter: {
      type: Object,
      default() {
        return {}
      }
    },
    // 课程详情接口返回的数据
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      loading: false,
      detail: {},
      status: {},
      questions: [],
      values: [], // 提交的答案
      messageInstance: null,
      exam: {},
      isStartExam: false, // 是否开始考试
      autoSubmitTimer: null, // 自动提交定时器
      checkStatusTimer: null, // 考试状态定时器
      examVisible: true
    }
  },
  watch: {
    isExamComplete(value) {
      this.examVisible = !value
    }
  },
  computed: {
    // 学期ID
    sid() {
      return this.$route.params.sid
    },
    // 课程ID
    cid() {
      return this.$route.params.cid
    },
    // 当前页面的ID
    pid() {
      return this.data.course_examination
    },
    // 是否是考试时间
    isExamTime() {
      // 大于开始时间，小于结束时间
      return this.status.examination_status === '20'
    },
    // 考试按钮
    startExamButtonText() {
      return this.status.examination_status === '90' ? '考试结束' : '开始考试'
    },
    // 考试完成
    isExamComplete() {
      // 考试完成，批改完成并且公布成绩
      return this.exam.is_published === 1 && this.exam.type === 2
    },
    // 是否提交
    isSubmited() {
      return this.exam.type === 1 || this.exam.type === 2
    },
    // 提交按钮文本
    submitText() {
      return this.isSubmited ? '已提交' : '提交'
    }
  },
  methods: {
    // 开始考试
    onStartExam() {
      this.isStartExam = true
      // 自动提交答题
      this.autoSubmit()
    },
    // 获取试题
    getDetail(callback) {
      this.loading = true
      api
        .getCourseExam(this.sid, this.cid)
        .then(response => {
          this.detail = Array.isArray(response) ? null : response
          // 设置问题列表数据
          this.questions = this.detail
            ? this.genQuenstions(this.detail.examination)
            : []
          callback && callback()
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 组装问题数据
    genQuenstions(data) {
      if (!data) {
        return
      }
      let { radioList, checkboxList, shortAnswerList } = data
      // 单选
      radioList = radioList.map(item => {
        const temp = {
          type: 1,
          formModel: { id: item.id, user_answer: item.user_answer || '' }
        }
        return Object.assign({}, item, temp)
      })
      // 多选
      checkboxList = checkboxList.map(item => {
        const temp = {
          type: 2,
          formModel: { id: item.id, user_answer: item.user_answer || [] }
        }
        return Object.assign({}, item, temp)
      })
      // 问答
      shortAnswerList = shortAnswerList.map(item => {
        const temp = {
          type: 3,
          formModel: {
            id: item.id,
            user_answer: item.user_answer
              ? Base64.decode(item.user_answer)
              : '',
            attachments: []
          }
        }
        return Object.assign({}, item, temp)
      })
      return [...radioList, ...checkboxList, ...shortAnswerList]
    },
    // 获取考试状态
    getExamStatus() {
      api.getCourseExamStatus(this.sid, this.cid, this.pid).then(response => {
        this.status = response
        if (this.isSubmited || response.examination_status === '90') {
          this.checkStatusTimer && clearInterval(this.checkStatusTimer)
        }
      })
    },
    // 自动获取考试状态
    autoCheckExamStatus() {
      // 获取试题状态
      this.getExamStatus()
      this.checkStatusTimer && clearInterval(this.checkStatusTimer)
      this.checkStatusTimer = setInterval(() => {
        this.getExamStatus()
      }, 3000)
    },
    // 获取考试结果
    getExamResult() {
      api.getCourseExamResult(this.sid, this.cid, this.pid).then(response => {
        // 设置问题列表数据
        if (response.code !== 8001) {
          this.isStartExam = true
          this.exam = response
          this.questions = this.genQuenstions(response.sheet)
          // 自动提交
          if (this.isStartExam && !this.isSubmited && !this.isExamComplete) {
            this.autoSubmit()
          }
        }
      })
    },
    // 提交校验
    checkSubmit() {
      const quenstions = this.questions
      for (let i = 0; i < quenstions.length; i++) {
        const value = quenstions[i].formModel.user_answer
        if (Array.isArray(value) ? !value.length : !value) {
          return false
        }
      }
      return true
    },
    // 提交
    onSubmit() {
      // 校验
      if (!this.checkSubmit()) {
        this.messageInstance && this.messageInstance.close()
        this.messageInstance = this.$message.error('还有题目未做，不能提交')
        return
      }
      // 提交的答案数据
      const answers = this.questions.map(item => {
        if (item.type === 3) {
          item.formModel.user_answer = Base64.encode(item.formModel.user_answer)
        }
        return item.formModel
      })
      // 提交参数
      const params = { answers: JSON.stringify(answers), type: 1 }
      // 请求接口
      this.handleSubmitRequest(params)
    },
    // 自动提交
    autoSubmit() {
      // 10秒提交一次
      this.autoSubmitTimer && clearInterval(this.autoSubmitTimer)
      this.autoSubmitTimer = setInterval(() => {
        // 提交的答案数据
        const answers = this.questions.map(item => {
          if (item.type === 3) {
            item.formModel.user_answer = Base64.encode(
              item.formModel.user_answer
            )
          }
          return item.formModel
        })
        const params = { answers: JSON.stringify(answers), type: 0 }
        // 请求接口
        this.handleSubmitRequest(params)
      }, 10000)
    },
    // 请求提交接口
    handleSubmitRequest(params) {
      api
        .submitCourseExam(this.sid, this.cid, this.pid, params)
        .then(response => {
          if (params.type === 0) {
            console.log('暂存成功')
            return
          }
          if (response.code === 200) {
            this.$message.success('考试答卷提交成功')
            this.autoSubmitTimer && clearInterval(this.autoSubmitTimer)
            this.getExamResult()
          } else {
            this.$message.error(response.data.error)
          }
        })
        .catch(error => {
          this.$message.error(error.message)
        })
    }
  },
  beforeMount() {
    // 获取试题
    this.getDetail(() => {
      // 获取考试结果
      this.getExamResult()
      // 自动获取考试状态
      this.autoCheckExamStatus()
    })
  },
  destroyed() {
    this.autoSubmitTimer && clearInterval(this.autoSubmitTimer)
    this.checkStatusTimer && clearInterval(this.checkStatusTimer)
  }
}
</script>

<style lang="scss" scoped>
.exam-buttons {
  padding: 40px 0;
  text-align: center;
  .el-button {
    width: 240px;
    margin: 40px auto;
  }
}
.no-exam {
  padding: 100px;
  font-size: 30px;
  text-align: center;
}
.exam-finish {
  margin: 40px 0;
}
.exam-table {
  width: 100%;
  border-collapse: collapse;
  th {
    background-color: #ccc;
  }
  td,
  th {
    padding: 10px;
    border: 1px solid #999;
    text-align: center;
  }
}
.exam-total {
  font-size: 18px;
  text-align: right;
  padding: 0 40px;
}
.exam-welcome {
  padding: 40px;
  line-height: 30px;
  text-align: center;
  ::v-deep .el-button {
    margin-top: 30px;
  }
}
</style>
