
<template>
  <container :title="chapter.name" v-loading="loading">
    <div class="exam-form">
      <el-form :disabled="isRevised">
        <exam-item
          v-for="(item, index) in questions"
          :index="index"
          :type="item.question_type"
          :data="item"
          :value="item.formModel"
          :disabled="isRevised"
          :key="item.id"
        ></exam-item>
      </el-form>
    </div>
    <div class="work-bottom" v-if="detail">
      <div class="info">
        <template v-if="isRevised">
          <div class="paper-check">
            <p>批改时间：{{detail.check_date}}</p>
            <div class="paper-check-item">
              <b>评分：</b>
              {{detail.score}}
            </div>
            <div class="paper-check-item">
              <b>评语：</b>
              <div class="edit_html" v-html="detail.check_comments"></div>
            </div>
          </div>
        </template>
        <template v-else-if="detail.created_time">
          <p class="help">已于 {{detail.created_time}} 提交，等待老师批改中。</p>
          <template v-if="detail.updated_time && detail.updated_time !== detail.created_time">
            <p class="help">最近提交时间： {{detail.updated_time}}</p>
          </template>
        </template>
      </div>
    </div>
    <div class="buttons">
      <el-tooltip content="在获老师批改之前，可以多次提交，将以最后一次提交为准" placement="right">
        <el-button type="primary" @click="onSubmit" :disabled="isRevised">{{submitText}}</el-button>
      </el-tooltip>
    </div>
  </container>
</template>

<script>
import Base64 from 'Base64'

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

// 章节作业
export default {
  name: 'ChapterWork',
  components: { Container, ExamItem },
  props: {
    // 当前选中的
    chapter: {
      type: Object,
      default() {
        return {}
      }
    },
    // 课程详情接口返回的数据
    data: {
      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
    },
    // 是否批改
    isRevised() {
      return this.detail ? !!this.detail.check_date : false
    },
    // 提交按钮文本
    submitText() {
      return this.isRevised ? '已批改' : '提交'
    }
  },
  methods: {
    // 获取详情
    getDetail() {
      this.loading = true
      api
        .getChapterExam(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) {
                item.user_answer = found.descreption
                item.attachments = found.file_url
              }
              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 answers = this.questions.map(item => {
        if (item.question_type === 3) {
          item.formModel.user_answer = Base64.encode(item.formModel.user_answer)
        }
        return {
          question_id: item.id,
          descreption: item.formModel.user_answer,
          file_url: item.formModel.attachments,
          is_encoded: 1
        }
      })
      // 提交参数
      const params = {
        semester_id: this.sid,
        course_id: this.cid,
        chapter_id: this.pid,
        work_id: this.resourceId,
        work_contents: JSON.stringify(answers),
        duration
      }
      // 请求接口
      this.handleSubmitRequest(params)
    },
    // 请求提交接口
    handleSubmitRequest(params) {
      api
        .sbumitChapterExam(params)
        .then(response => {
          if (response.status) {
            this.$message.success('提交成功，等待批改')
            this.getDetail()
          } else {
            this.$message.error(response.data.error)
          }
        })
        .catch(error => {
          this.$message.error(error.message)
        })
    }
  },
  beforeMount() {
    this.getDetail()
  }
}
</script>
