<template>
  <div v-loading="page_is_loading" class="exam-paper">
    <div
      class="aq-card"
      ref="AQCard"
      v-if="mode === 0 || mode === 3 || mode === 1"
    >
      <AQCard
        :questions="questions"
        :flag="flagList"
        :answers="answers"
        @smooth="aqItemOnClick"
        :mode="mode"
        @cancel="onPreviewCancel"
      ></AQCard>
    </div>
    <div class="questions-area">
      <h1 style="text-align: center; padding: 10px 0; font-size: 18px">
        {{ exam?.title }}
      </h1>
      <QuestionsList
        :questions="questions"
        @flag="flagListChanged"
        @answers="userAnswerChanged"
        :mode="mode"
        :paperStyle="mode == 0 ? exam?.examMode : 0"
        ref="questionList"
        @evalChanged="evalListChanged"
        :random="random"
      ></QuestionsList>
    </div>
    <div class="tips-card" v-if="mode === 0">
      <StudentTips
        :answers="answers"
        :historyInfo="onlineExamInfo"
        :questions="questions"
        :now="now"
        @submit="submitThisExamBtnHandler"
        @forceSubmit="forceSubmitHandler"
        @cancel="cancelThisExamBtnHandler"
        :mode="mode"
      >
      </StudentTips>
    </div>
    <div class="tips-card" v-if="mode === 3">
      <TeacherTips
        @cancel="cancelThisExamBtnHandler"
        :onlyMistake.sync="onlyMistake"
        :evalList="evalList"
        :onlyTextarea.sync="onlyTextarea"
        :logs="allStudentExamLogs"
        :questions="questions"
        @submit="submitEval"
      ></TeacherTips>
    </div>
  </div>
</template>

<script>
import {
  getOnlineExamAllDataApi,
  submitExamApi,
  getOnlineExamResultApi
} from '@/api/assessment-evaluation/onlineTest'
import {
  pagingGradeDetailsApi,
  patchSomeExamResult
} from '@/api/assessment-evaluation/humanEval'
import AQCard from './components/AQCard.vue'
import QuestionsList from './components/QuestionsList.vue'
import StudentTips from './components/StudentTips.vue'
import TeacherTips from './components/TeacherDatas.vue'
export default {
  components: { AQCard, QuestionsList, StudentTips, TeacherTips },
  data: () => ({
    page_is_loading: false,
    exam: null,
    paper: null,
    onlineExamInfo: null,
    questions: [],
    questionsBak: [],
    classifyQuestions: {},
    flagList: [],
    random: [0, 0],
    answers: [],
    mode: -1,
    allStudentExamLogs: [],
    onlyMistake: false,
    onlyTextarea: false,
    evalList: [],
    now: 0
  }),
  mounted () {
    this.initMode()
  },
  activated () {
    this.initPage()
  },
  watch: {
    onlyMistake: {
      handler (nv) {
        this.filterQuestion()
      }
    },
    onlyTextarea: {
      handler (nv) {
        this.filterQuestion()
      }
    },
    '$route.params.studentExamId': {
      handler (nv) {
        this.initPage()
      }
    }
  },
  methods: {
    // 根据错题和简答题过滤试题
    filterQuestion () {
      let question = this.questionsBak
      if (this.mode === 3) {
        if (this.onlyMistake) {
          question = question.filter((item) => item.userScore < item.score)
        }
        if (this.onlyTextarea) {
          question = question.filter((item) =>
            [
              'textarea'
              // , 'input'
            ].includes(item.element)
          )
        }
        this.questions = question
      }
    },
    /*
      取消预览,返回上一页
    */
    onPreviewCancel () {
      this.$router.go(-1)
    },
    // getPdf,
    submitEval () {
      this.page_is_loading = true
      patchSomeExamResult(this.onlineExamInfo.id, this.evalList)
        .then((res) => {
          this.$message.success('提交成功')
          this.evalList = []
        })
        .catch(() => {})
        .finally((_) => {
          this.page_is_loading = false
        })
    },
    evalListChanged (nv) {
      this.evalList = nv
    },
    onlyMistakeHandler (v) {},
    /*
      初始化页面的handler
    */
    initPage () {
      this.initAlldata()
      this.initMode()
      if (this.mode === 0) {
        this.getAllData()
      } else if (this.mode === 3) {
        this.getResultData()
      } else {
        this.getResultData()
      }
    },
    /*
      获取所有学员考试记录
      */
    getAllStudentExamLogs (examId) {
      pagingGradeDetailsApi({ id: examId }).then((res) => {
        this.allStudentExamLogs = res.data.data
      })
    },
    // 设置模式
    initMode () {
      if (this.$route.query.preview === '1') {
        this.mode = 1
      } else if (this.$route.query.preview === '3') {
        this.mode = 3
      } else {
        this.mode = 0
      }
    },
    /*
      初始化所有数据
    */
    initAlldata () {
      this.questions = []
      this.questionsBak = []
      this.classifyQuestions = {}
      this.flagList = []
      this.answers = []
      this.evalList = []
      this.random = [0, 0]
      this.exam = null
      this.paper = null
      this.onlineExamInfo = null
      this.page_is_loading = false
    },
    /*
      考试时间结束,强制交卷
    */
    forceSubmitHandler () {
      this.$message.warning('考试结束时间到，将会强制提交答卷！')
      this.submitExam()
    },
    /*
      点击交卷按钮后的cb
    */
    submitThisExamBtnHandler () {
      if (this.answers.length < this.questions.length) {
        return this.$confirm('还有题目未完成，是否强制交卷', '警告', {
          type: 'warning'
        })
          .then((res) => {
            this.submitExam()
          })
          .catch((_) => {})
      }
      if (this.flagList.length > 0) {
        return this.$confirm('有标记题目未取消，是否提交试卷', '警告', {
          type: 'warning'
        })
          .then((res) => {
            this.submitExam()
          })
          .catch((_) => {})
      }
      this.submitExam()
    },
    /*
      点击退出考试按钮后的cb
    */
    cancelThisExamBtnHandler () {
      if (this.mode === 3) {
        return this.$router.go(-1)
      }
      return this.$confirm('未完成试卷，是否退出考试！', '警告', {
        type: 'error'
      })
        .then((res) => {
          if (this.exam.classifyId === -1) {
            return this.$router.replace({
              path: '/assessment-evaluation/simulation-test'
            })
          }
          this.$router.replace({ path: '/assessment-evaluation/online-test' })
        })
        .catch((_) => {})
    },
    /*
      提交试卷api
     */
    submitExam () {
      if (!this.$route.params.studentExamId) return
      submitExamApi({
        id: this.$route.params.studentExamId,
        answers: this.answers
      }).then((res) => {
        const tipText = ` 试卷总分：${
          res.data.paperScore
        }分，及格分:${Math.ceil(
          (res.data.paperScore * res.data.passPercent) / 100
        )}分，您的成绩：${res.data.score}分`
        if (res.data.gradePaperMode === 0) {
          this.$confirm(
            res.data.isPass
              ? this.exam.successTips + tipText
              : this.exam.failedTips + tipText,
            '提示',
            { type: res.data.isPass ? 'success' : 'error' }
          ).finally((_) => {
            if (this.exam.classifyId === -1) {
              return this.$router.replace({
                path: '/assessment-evaluation/simulation-test'
              })
            }
            this.$router.replace({
              path: '/assessment-evaluation/online-test'
            })
          })
        } else if (res.data.gradePaperMode === 1) {
          this.$confirm(this.exam.waitingTips, '提示', {
            type: 'info'
          }).finally((_) => {
            if (this.exam.classifyId === -1) {
              return this.$router.replace({
                path: '/assessment-evaluation/simulation-test'
              })
            }
            this.$router.replace({
              path: '/assessment-evaluation/online-test'
            })
          })
        }
      })
    },
    /*
      左侧栏目试题被点击,试卷滚动或切换到试题,并闪烁题目,
    */
    aqItemOnClick (question) {
      if (+this.exam.examMode === 0) {
        const item = document.querySelector(`[tag="${question.id}"]`)
        item.scrollIntoView({
          block: 'start',
          behavior: 'smooth'
        })
        item.classList.add('shine')
        setTimeout(() => {
          item.classList.remove('shine')
        }, 2000)
      } else if (+this.exam.examMode === 1) {
        this.$refs.questionList.changeIndById(question.id)
      }
    },
    /*
      用户答案修改后回调
    */
    userAnswerChanged (nv) {
      this.answers = nv
    },
    /*
      用户标记试题列表被修改的回调
    */
    flagListChanged (nv) {
      this.flagList = nv
    },
    /*
      开始考试
    */
    getAllData () {
      if (!this.$route.params.studentExamId) return
      this.page_is_loading = true
      getOnlineExamAllDataApi(this.$route.params.studentExamId)
        .then((res) => {
          const { exam, onlineExamInfo, paper, questions, now } = res.data
          this.exam = exam
          this.onlineExamInfo = onlineExamInfo
          this.questions = questions
          this.questionsBak = questions
          this.now = now
          this.random = [
            paper.questionsIsRandomSort,
            paper.optionsIsRandomSort
          ]
          if (this.random[0] === 1) {
            this.questions.sort(() => Math.random() - 0.5)
            this.questions.sort((a, b) => a.typeId - b.typeId)
          }
        })
        .catch((_) => {
          // 后端校验是否可以考试，不可以考试则退出到列表
          if (this.exam.classifyId === -1) {
            return this.$router.replace({
              path: '/assessment-evaluation/simulation-test'
            })
          }
          this.$router.replace({ path: '/assessment-evaluation/online-test' })
        })
        .finally((_) => {
          this.page_is_loading = false
        })
    },
    /*
    查看答卷
    */
    getResultData () {
      if (!this.$route.params.studentExamId) return
      this.page_is_loading = true
      getOnlineExamResultApi(this.$route.params.studentExamId)
        .then((res) => {
          const { exam, onlineExamInfo, questions } = res.data
          this.exam = exam
          this.getAllStudentExamLogs(exam.id)
          this.onlineExamInfo = onlineExamInfo
          this.questions = questions
          this.questionsBak = questions
          this.random = [0, 0]
        })
        .catch((_) => {
          this.$router.go(-1)
        })
        .finally((_) => {
          this.page_is_loading = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.exam-paper {
  display: flex;
  height: 100%;
  position: relative;

  .aq-card {
    flex-basis: 240px;
    flex-shrink: 0;
    width: 240px;
    padding-right: 15px;
    border-right: 1px solid #efefef;
    height: 100%;
    overflow-y: scroll;
  }

  .tips-card {
    flex-basis: 200px;
    width: 200px;
    padding-left: 15px;
    border-left: 1px solid #efefef;
    flex-shrink: 0;
  }

  .questions-area {
    height: 100%;
    flex-grow: 1;
    overflow-y: scroll;
    padding: 0 20px;
  }
}
</style>
