<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>
      <!-- 有互评的，批改后不显示 -->
      <template v-if="!(hasComment && isRevised)">
        <p style="color: red" v-if="deadline && ![0, 1].includes(detail.status)">
          {{ $t('viewerWork.deadline', { date: deadline }) }}
        </p>
        <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-button type="primary" :disabled="disabled" :loading="submitLoading" @click="onSubmit">
            {{ submitText }}
          </el-button>
          <!-- 驳回 -->
          <template v-if="detail.status === 1">
            <span>提交后不可修改，请检查好作业内容再做提交。</span>
          </template>
          <template v-else>
            <span v-if="hasComment && !isRevised">{{ $t('viewerWork.commentTips') }}</span>
          </template>
        </div>
      </template>
    </container>

    <chapter-work-comment
      id="comment"
      :endDate="commentEndDate"
      :status="detail.status2"
      @update="$emit('updateHomework')"
      v-if="showComment"
    >
      <!-- 已批改 -->
      <template v-if="isRevised">
        <div class="work-bottom">
          <div class="info">
            <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>
          </div>
        </div>
        <div class="buttons">
          <el-button type="primary" :disabled="disabled">{{ submitText }}</el-button>
        </div>
      </template>
    </chapter-work-comment>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" top="0">
      <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: () => ({}) },
    // 课程详情接口返回的数据
    data: { type: Object, default: () => ({}) },
    homework: { type: Object, default: () => ({}) }
  },
  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: {
    homework: {
      immediate: true,
      handler(data) {
        const { questions = [], answer = {} } = data
        this.questions = this.genQuestions(questions)
        this.detail = Array.isArray(answer) ? {} : answer
        if (
          (this.detail.status === 1 || this.detail.status2 === 1) &&
          !([-1, -2].includes(this.detail.status) || [-1, -2].includes(this.detail.status2))
        ) {
          this.dialogVisible = true
        }
        // 答案处理
        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
    },
    // 是否批改
    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 && this.detail.status !== 1
    },
    disabled() {
      return this.detail.status === 0
      // 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 !== 0
        this.isAnonymous = !!response.anonymous
        this.hasComment = !!response.comment
        this.commentEndDate = response.comment_end
      })
    },
    // 组装问题数据
    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) {
          item.user_answer = found.descreption
          item.attachments = found.file_url
        }
        return item
      })
      // 重新组装数据
      this.questions = this.genQuestions(this.questions)
    },
    // 提交校验
    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.$emit('updateHomework')
          } 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.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;
  }
}
::v-deep .el-dialog {
  top: 50%;
  transform: translateY(-50%);
}
</style>
