<template>
  <container :title="chapter.name" v-loading="loading">
    <template v-slot:header-aside v-if="isSubmited">正确率：{{detail.score}}%</template>
    <div class="exam">
      <div class="exam-form">
        <el-form :disabled="isSubmited">
          <exam-item
            v-for="(item, index) in unorderedQuestions"
            :index="index"
            :type="item.question_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>
    </div>
  </container>
</template>

<script>
// libs
import { shuffle } from 'lodash'
// components
import Container from '../common/container.vue'
import ExamItem from './examItem.vue'
// api
import * as api from '../../api'

// 章节测试题
export default {
  name: 'ChapterTest',
  components: { Container, ExamItem },
  props: {
    // 当前选中的章节
    chapter: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      loading: false,
      detail: null,
      questions: [], // 问题列表
      startTime: new Date().getTime(), // 进入时间
      messageInstance: null
    }
  },
  watch: {
    chapter: {
      immediate: true,
      handler(data) {
        this.questions = data.homework
          ? this.genQuenstions(data.homework.questions)
          : []
      }
    }
  },
  computed: {
    // 学期ID
    sid() {
      return this.$route.params.sid
    },
    // 课程ID
    cid() {
      return this.$route.params.cid
    },
    // 当前页面的ID
    pid() {
      return this.$route.params.id
    },
    // 资源ID
    resourceId() {
      return this.chapter.resource_id
    },
    // 打乱顺序的问题列表
    unorderedQuestions() {
      const ids = this.questions.map(item => item.id)
      const sortIds = shuffle(ids)
      return sortIds.map(id => this.questions.find(item => item.id === id))
    },
    // 是否提交
    isSubmited() {
      return this.detail ? !!this.detail.work_contents : false
    },
    // 提交按钮文本
    submitText() {
      return this.isSubmited ? '已提交' : '提交'
    }
  },
  methods: {
    // 获取测试答题详情
    getDetail() {
      this.loading = true
      api
        .getChapterHomework(this.sid, this.cid, this.resourceId)
        .then(response => {
          this.detail = Array.isArray(response) ? null : response
          if (this.detail) {
            const parseAnswers = JSON.parse(this.detail.work_contents)
            // 设置答案
            this.questions = this.questions.map(item => {
              const found = parseAnswers.find(
                answer => answer.question_id === item.id
              )
              if (found) {
                const selectedIds = found.options.reduce((result, item) => {
                  item.selected && result.push(item.id)
                  return result
                }, [])
                item.user_answer =
                  item.question_type === 2 ? selectedIds : selectedIds[0]
              }
              return item
            })
            this.questions = this.genQuenstions(this.questions)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 组装问题数据
    genQuenstions(list) {
      if (!list) {
        return []
      }
      return list.map(item => {
        let temp = null
        if (item.question_type === 1) {
          // 单选
          temp = {
            formModel: { id: item.id, user_answer: item.user_answer || '' }
          }
        } else if (item.question_type === 2) {
          // 多选
          temp = {
            formModel: { id: item.id, user_answer: item.user_answer || [] }
          }
        } else if (item.question_type === 3) {
          // 简答
          temp = {
            formModel: {
              id: item.id,
              user_answer: item.user_answer
                ? Base64.decode(item.user_answer)
                : '',
              attachments: item.attachments || ''
            }
          }
        }
        return Object.assign(
          {},
          item,
          {
            content: item.question_content,
            options: item.question_options
              ? JSON.parse(item.question_options)
              : []
          },
          temp
        )
      })
    },
    // 提交校验
    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 duration = Math.floor(
        (new Date().getTime() - this.startTime) / 1000
      )
      // 答案数据
      const data = this.handleSubmitData()
      // 计算分数
      const score = data.reduce((result, item) => {
        item.is_correct && result++
        return result
      }, 0)
      const total = this.questions.length
      const params = {
        semester_id: this.sid,
        course_id: this.cid,
        chapter_id: this.pid,
        work_id: this.resourceId,
        work_contents: JSON.stringify(data),
        duration,
        score: ((score / total) * 100).toFixed(1)
      }
      // 请求接口
      this.handleSubmitRequest(params)
    },
    // 提交的答案数据
    handleSubmitData() {
      const result = this.questions.map(item => {
        // 设置提交选中状态
        let isCorrect = true
        const options = item.options.map(option => {
          // 选择的项
          const answers = item.formModel.user_answer
          // 是否选中该项
          const selected = Array.isArray(answers)
            ? answers.includes(option.id)
            : option.id === answers
          // 是否选择正确
          if (option.checked !== selected && isCorrect) {
            isCorrect = false
          }
          return {
            id: option.id,
            checked: option.checked,
            option: option.option,
            selected
          }
        })
        return {
          question_id: item.id,
          is_correct: isCorrect ? 1 : 0,
          options
        }
      })
      return result
    },
    // 请求提交接口
    handleSubmitRequest(params) {
      api
        .sbumitChapterHomework(params)
        .then(response => {
          if (response.status) {
            this.getDetail()
          } else {
            this.$message.error(response.data.error)
          }
        })
        .catch(error => {
          this.$message.error(error.message)
        })
    }
  },
  beforeMount() {
    this.getDetail()
  }
}
</script>

<style lang="scss" scoped>
.exam-buttons {
  padding: 40px 0;
  text-align: center;
  .el-button {
    width: 240px;
    margin: 40px auto;
  }
}
</style>
