<template>
  <container :title="chapter.name" v-loading="loading">
    <template v-slot:header-aside v-if="isSubmited">{{ $t('viewerWork.correctRate') }}：{{ detail.score }}%</template>
    <div class="exam">
      <div class="exam-form">
        <el-form :disabled="isSubmited">
          <exam-item
            v-for="(item, index) in questions"
            :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="$t('viewerWork.examSubmitButtonTips')" placement="right">
              <el-button type="primary" :loading="submitLoading" @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: () => ({}) },
    homework: { type: Object, default: () => ({}) }
  },
  data() {
    return {
      loading: false,
      detail: null,
      questions: [], // 问题列表
      startTime: new Date().getTime(), // 进入时间
      messageInstance: null,
      submitLoading: false
    }
  },
  watch: {
    homework: {
      immediate: true,
      handler(data) {
        const { questions = [], answer = {} } = data
        this.detail = answer
        this.questions = this.genQuestions(questions)
        // 答案处理
        const parseAnswers = answer.work_contents ? JSON.parse(answer.work_contents) : []
        if (parseAnswers && parseAnswers.length) {
          this.setAnswers(parseAnswers)
        }
      }
    }
  },
  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 ? this.$t('viewerWork.submitedText') : this.$t('viewerWork.submitText')
    }
  },
  methods: {
    // 组装问题数据
    genQuestions(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
        )
      })
    },
    // 设置答案
    setAnswers(parseAnswers) {
      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.genQuestions(this.questions)
    },
    // 提交校验
    checkSubmit() {
      const questions = this.questions
      if (!questions.length) {
        return
      }
      for (let i = 0; i < questions.length; i++) {
        const value = questions[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(this.$t('viewerWork.examSubmitError'))
        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) {
      this.submitLoading = true
      api
        .sbumitChapterHomework(params)
        .then(response => {
          if (response.status) {
            this.$emit('updateHomework')
          } else {
            this.$message.error(response.data.error)
          }
        })
        .catch(error => {
          this.$message.error(error.message)
        })
        .finally(() => {
          this.submitLoading = false
        })
    }
  }
}
</script>

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