<template>
  <div>
    <container :title="chapter.name" v-loading="loading" id="work">
      <template v-slot:header-aside v-if="isRevised">
        <p v-if="hasScore">{{ $t('viewerWork.score') }}：{{ detail.score }}{{ $t('viewerWork.fractionUnit') }}</p>
      </template>
      <div class="exam-form">
        <template v-for="(item, index) in questions">
          <el-form :disabled="disabled" :key="item.id" ref="form" :model="item.formModel" :rules="rules">
            <el-form-item prop="user_answer">
              <exam-item
                :index="index"
                :type="item.question_type"
                :data="item"
                :value="item.formModel"
                :disabled="disabled"
                :hasUpload="hasUpload"
              ></exam-item>
            </el-form-item>
          </el-form>
        </template>
      </div>
      <p style="color: red" v-if="deadline && detail.status !== 1">
        {{ $t('viewerWork.deadline', { date: deadline }) }}
      </p>
      <!-- 驳回状态 -->
      <template v-if="detail.status === 8">
        <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">{{ $t('viewerWork.reEdit') }}</el-button>
        </div>
      </template>
      <!-- 正常状态 -->
      <template v-else>
        <div class="work-bottom" v-if="detail.status !== 1">
          <div class="info">
            <template v-if="isRevised">
              <div class="paper-check">
                <p>{{ $t('viewerWork.correctionTime') }}：{{ detail.checker_time }}</p>
                <div class="paper-check-item" v-if="hasScore">
                  <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" :loading="submitLoading" @click="onSubmit">{{
              submitText
            }}</el-button>
          </el-tooltip>
          <!-- 驳回 -->
          <template v-if="detail.status === 1">
            <span>提交后不可修改，请检查好作业内容再做提交。</span>
          </template>
          <template v-else>
            <span v-if="hasComment">{{ $t('viewerWork.commentTips') }}</span>
          </template>
        </div>
      </template>
    </container>

    <chapter-work-comment
      :endDate="commentEndDate"
      :status="detail.status2"
      @update="getDetail"
      v-if="showComment"
      id="comment"
    />

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <div class="paper-check-item">
        <p>您本次的作业被老师驳回，请您重新编辑作业提交！</p>
      </div>
      <div class="paper-check-item">
        <span>{{ $t('viewerWork.rejectTime') }}：</span>
        {{ detail.checker_time }}
      </div>
      <div class="paper-check-item">
        <span>{{ $t('viewerWork.rejectContent') }}：</span>
        <div class="edit_html" v-html="detail.check_comments"></div>
      </div>
      <template #footer>
        <div style="text-align: center">
          <el-button type="primary" @click="onReEdit">重新编辑</el-button>
          <p style="margin-top: 16px; color: #f00">注：重新提交后不可修改，请检查好作业内容再做提交。</p>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import Base64 from 'Base64'

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

// 章节作业
export default {
  name: 'ChapterWork',
  components: { Container, ExamItem, ChapterWorkComment },
  props: {
    // 当前选中的
    chapter: {
      type: Object,
      default() {
        return {}
      }
    },
    // 课程详情接口返回的数据
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      loading: false,
      detail: {},
      questions: [], // 问题列表
      startTime: new Date().getTime(), // 进入时间
      messageInstance: null,
      deadline: '', // 截止时间
      submitLoading: false,
      hasUpload: true, // 是否可以上传
      isAnonymous: false, // 是否匿名
      hasComment: false, // 是否评论
      commentEndDate: '',
      rules: {
        user_answer: [{ required: true, message: '请输入', trigger: 'change' }]
      },
      dialogVisible: false,
      popoverVisible: false
    }
  },
  watch: {
    chapter: {
      immediate: true,
      handler(data) {
        if (!this.questions.length) {
          this.questions = data.homework ? this.genQuestions(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.status === 0
    },
    // 提交按钮文本
    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
    },
    hasScore() {
      // allow_score  1 显示  2隐藏
      return this.detail.allow_score !== 2 && this.detail.score
    },
    // 显示作业评论
    showComment() {
      const currentTime = new Date().getTime()
      const endTime = +new Date(this.deadline)
      return this.hasComment && currentTime > endTime
    },
    disabled() {
      if (this.detail.status === 1) {
        return false
      }
      // -1未处理  0已处理   1驳回
      return this.detail.status === 0 || !this.isWorkTime
    },
    dialogTitle() {
      if (this.detail.status === 1 && this.detail.status2 === 1) {
        return '作业、互评作业驳回'
      }
      if (this.detail.status === 1) {
        return '作业驳回'
      }
      if (this.detail.status2 === 1) {
        return '互评作业驳回'
      }
    }
  },
  methods: {
    // 获取作业截止时间
    getDeadline() {
      api.getChapterHomeworkDeadline(this.sid, this.cid, this.pid).then(response => {
        this.deadline = response.dead_line
        this.hasUpload = !!response.pdf
        this.isAnonymous = !!response.anonymous
        this.hasComment = !!response.comment
        this.commentEndDate = response.comment_end
      })
    },
    // 获取详情
    getDetail() {
      this.loading = true
      api
        .getChapterHomework(this.sid, this.cid, this.resourceId)
        .then(response => {
          this.detail = Array.isArray(response) ? {} : response
          if (
            (this.detail.status === 1 || this.detail.status2 === 1) &&
            !([-1, -2].includes(this.detail.status) || [-1, -2].includes(this.detail.status2))
          ) {
            this.dialogVisible = true
          }
          if (this.detail.id) {
            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.genQuestions(this.questions)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 组装问题数据
    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
        )
      })
    },
    // 提交校验
    checkSubmit() {
      let result = true
      for (let i = 0; i < this.questions.length; i++) {
        this.$refs.form[i].validate(valid => {
          if (!valid) {
            result = valid
            return result
          }
        })
      }
      return result
    },
    // 提交
    onSubmit() {
      // 校验
      if (!this.checkSubmit()) {
        this.messageInstance && this.messageInstance.close()
        this.messageInstance = this.$message.error(this.$t('viewerWork.examSubmitError'))
        return
      }
      // 驳回提交
      if (this.detail.status === 1) {
        this.$confirm('本次作业提交后不可修改，您确认提交吗？', '提示', {
          confirmButtonText: '确定提交',
          type: 'warning'
        }).then(this.handleSubmit)
      } else {
        // 正常提交
        this.handleSubmit()
      }
    },
    handleSubmit() {
      // 计算答题时间
      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.dialogVisible = false
      if (this.detail.status === 1) {
        window.location.hash = '#work'
        return
      }
      if (this.detail.status2 === 1) {
        window.location.hash = '#comment'
      }
    }
  },
  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 {
  padding: 5px 0;
  display: flex;
  b,
  span {
    white-space: nowrap;
  }
}
</style>
