<template>
  <container :title="chapter.name" v-loading="loading">
    <div class="exam-form">
      <el-form :disabled="disabled || !isWorkTime">
        <exam-item
          v-for="(item, index) in questions"
          :index="index"
          :type="item.question_type"
          :data="item"
          :value="item.formModel"
          :disabled="disabled || !isWorkTime"
          :key="item.id"
        ></exam-item>
      </el-form>
    </div>
    <p style="color: red" v-if="deadline">{{ $t('viewerWork.deadline', { deadline }) }}</p>
    <!-- 驳回状态 -->
    <template v-if="detail && detail.status === 1">
      <div class="work-bottom">
        <div class="info">
          <div class="paper-check">
            <h4>{{ $t('viewerWork.rejectTips') }}</h4>
            <div class="paper-check-item">
              <b>{{ $t('viewerWork.rejectTime') }}：</b>
              {{ detail.checker_time }}
            </div>
            <div class="paper-check-item">
              <b>{{ $t('viewerWork.rejectContent') }}：</b>
              <div class="edit_html" v-html="detail.check_comments"></div>
            </div>
          </div>
        </div>
      </div>
      <div class="buttons">
        <el-button type="primary" @click="onReEdit" :disabled="!isWorkTime">{{ $t('viewerWork.reEdit') }}</el-button>
      </div>
    </template>
    <!-- 正常状态 -->
    <template v-else>
      <div class="work-bottom" v-if="detail">
        <div class="info">
          <template v-if="isRevised">
            <div class="paper-check">
              <p>{{ $t('viewerWork.correctionTime') }}：{{ detail.checker_time }}</p>
              <div class="paper-check-item">
                <b>{{ $t('viewerWork.score') }}：</b>
                {{ detail.score }}
              </div>
              <div class="paper-check-item">
                <b>{{ $t('viewerWork.comments') }}：</b>
                <div class="edit_html" v-html="detail.check_comments"></div>
              </div>
            </div>
          </template>
          <template v-else-if="detail.created_time">
            <p class="help">{{ $t('viewerWork.submitted', { time: detail.created_time }) }}</p>
            <template v-if="detail.updated_time && detail.updated_time !== detail.created_time">
              <p class="help">{{ $t('viewerWork.submitDateTime') }}： {{ detail.updated_time }}</p>
            </template>
          </template>
        </div>
      </div>
      <div class="buttons">
        <el-tooltip :content="$t('viewerWork.workSubmitButtonTips')" placement="right">
          <el-button type="primary" :disabled="disabled || !isWorkTime" :loading="submitLoading" @click="onSubmit">{{
            submitText
          }}</el-button>
        </el-tooltip>
      </div>
    </template>
  </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,
      deadline: '', // 截止时间
      disabled: false,
      submitLoading: false
    }
  },
  watch: {
    chapter: {
      immediate: true,
      handler(data) {
        if (!this.questions.length) {
          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.status === 0 : false
    },
    // 提交按钮文本
    submitText() {
      return this.isRevised ? this.$t('viewerWork.revisedButtonText') : this.$t('viewerWork.submitText')
    },
    // 是否是提交作业时间
    isWorkTime() {
      if (!this.deadline) {
        return true
      }
      // 大于开始时间，小于结束时间
      const endTime = +new Date(this.deadline)
      const currentTime = new Date().getTime()
      return currentTime < endTime
    }
  },
  methods: {
    // 获取作业截止时间
    getDeadline() {
      api.getChapterHomeworkDeadline(this.sid, this.cid, this.pid).then(response => {
        this.deadline = response.dead_line
      })
    },
    // 获取详情
    getDetail() {
      this.loading = true
      api
        .getChapterHomework(this.sid, this.cid, this.resourceId)
        .then(response => {
          this.detail = Array.isArray(response) ? null : response
          if (this.detail) {
            // -1未处理  0已处理   1驳回
            this.disabled = [0, 1].includes(this.detail.status)
            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(this.$t('viewerWork.examSubmitError'))
        return
      }
      // 计算答题时间
      const duration = Math.floor((new Date().getTime() - this.startTime) / 1000)
      // 提交的答案数据
      const answers = this.questions.map(item => {
        return {
          question_id: item.id,
          descreption:
            item.question_type === 3 ? Base64.encode(item.formModel.user_answer) : 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) {
      this.submitLoading = true
      api
        .sbumitChapterHomework(params)
        .then(response => {
          if (response.status) {
            this.$message.success(this.$t('viewerWork.examSubmitSuccess'))
            this.getDetail()
          } else {
            this.$message.error(response.data.error)
          }
        })
        .catch(error => {
          this.$message.error(error.message)
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    // 重新编辑
    onReEdit() {
      this.disabled = false
      this.detail.status = -1
    }
  },
  beforeMount() {
    this.getDetail()
    this.getDeadline()
  }
}
</script>

<style lang="scss" scoped>
.work-bottom {
  margin-top: 20px;
  .info {
    color: #999;
    line-height: 28px;
  }
}
.buttons {
  padding: 20px 0;
  ::v-deep .el-button {
    width: 120px;
  }
}
.paper-check {
  padding: 10px;
  color: #000;
  border: 1px solid #dedede;
  h4 {
    margin: 0 0 10px;
  }
}
.paper-check-item {
  display: flex;
  b {
    white-space: nowrap;
  }
}
</style>
