<template>
  <container :title="chapter.name" v-loading="loading">
    <div class="exam">
      <div class="exam-form">
        <el-form :disabled="isSubmited" size="medium">
          <chapter-exam-item
            v-for="(item, index) in unorderedQuestions"
            :disabled="isSubmited"
            :data="item"
            :value="findAnswerById(item.id)"
            :index="index"
            :key="item.id"
            @change="onChange(item.id, ...arguments)"
          ></chapter-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 '../../components/container.vue'
import ChapterExamItem from './chapterExamItem.vue'
// api
import * as api from '../../api/index'

// 章节测试题
export default {
  name: 'ChapterExam',
  components: { Container, ChapterExamItem },
  props: {
    // 当前选中的章节
    chapter: { type: Object, default: () => {} }
  },
  data() {
    return {
      loading: false,
      detail: null,
      values: [], // 提交的答案
      startTime: new Date().getTime(), // 进入时间
      messageInstance: null
    }
  },
  computed: {
    // 学期ID
    sid() {
      return '6552021107166150656'
    },
    // 课程ID
    cid() {
      return '6568035374902280192'
    },
    // 当前页面的ID
    pid() {
      return this.$route.params.id
    },
    // 资源ID
    resourceId() {
      return this.chapter.resource_id
    },
    // 问题列表
    questions() {
      const homework = this.chapter.homework
      return homework ? homework.questions : []
    },
    // 打乱顺序的问题列表
    unorderedQuestions() {
      const ids = this.questions.map(item => item.id)
      const sortIds = shuffle(ids)
      return sortIds.map(id => this.questions.find(item => item.id === id))
    },
    /**
     * 解析用户提交的数据
     * @return [{{ question_id: 'xxx', value: ['xxx', 'xxx'] }}]
     */
    answers() {
      const answers = this.isSubmited
        ? JSON.parse(this.detail.work_contents)
        : []
      return answers.map(item => {
        const ids = item.options.reduce((result, subitem) => {
          subitem.selected && result.push(subitem.id)
          return result
        }, [])
        return { question_id: item.question_id, value: ids }
      })
    },
    // 是否提交
    isSubmited() {
      return this.detail ? !!this.detail.work_contents : false
    },
    // 提交按钮文本
    submitText() {
      return this.isSubmited ? '已提交' : '提交'
    }
  },
  methods: {
    // 获取测试答题详情
    getDetail() {
      this.loading = true
      api
        .getChapterExam(this.sid, this.cid, this.resourceId)
        .then(response => {
          this.detail = Array.isArray(response) ? null : response
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 通过问题ID查找答案
    findAnswerById(id) {
      const found = this.answers.find(item => item.question_id === id)
      return found ? found.value : []
    },
    onChange(qid, value) {
      const index = this.values.findIndex(item => item.question_id === qid)
      if (index === -1) {
        this.values.push({ question_id: qid, value })
      } else {
        this.values.splice(index, 1, { question_id: qid, value })
      }
    },
    // 提交校验
    checkSubmit() {
      if (this.values.length !== this.questions.length) {
        return false
      }
      const values = this.values
      for (let i = 0; i < values.length; i++) {
        const options = values[i].value
        if (!options.length) {
          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 => {
        // 查找提交的option id
        const found = this.values.find(
          subitem => subitem.question_id === item.id
        )
        const ids = found ? found.value : []
        // 解析
        const parseOptions = JSON.parse(item.question_options)
        // 设置提交选中状态
        let isCorrect = true
        const options = parseOptions.map(option => {
          option.selected = ids.includes(option.id) ? 1 : 0
          if (option.checked !== !!option.selected && isCorrect) {
            isCorrect = false
          }
          return option
        })
        return {
          question_id: item.id,
          is_correct: isCorrect ? 1 : 0,
          options
        }
      })
      return result
    },
    // 请求提交接口
    handleSubmitRequest(params) {
      api.sbumitChapterExam(params).then(response => {
        if (response.status) {
          this.getDetail()
        } else {
          this.$message.error(response.data.error)
        }
      })
    }
  },
  beforeMount() {
    this.getDetail()
  }
}
</script>

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