<script setup lang="ts">
import type { PaperQuestionType } from '@/types'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeftBold } from '@element-plus/icons-vue'
import { cachePaper, submitPaper } from '../api'

import CourseExamQuestion from './CourseExamQuestion.vue'
import CourseExamQuestionNumbers from './CourseExamQuestionNumbers.vue'

import { useLog } from '@/composables/useLog'
const log = useLog()

interface Props {
  status: number
  title?: string
  submitButtonText?: string
}
const props = withDefaults(defineProps<Props>(), { title: '考试/测验', submitButtonText: '交卷' })

const emit = defineEmits<{
  (e: 'update'): void
}>()

const route = useRoute()
const courseId = $ref(route.query.course_id as string)
const semesterId = $ref(route.query.semester_id as string)
const paperId = $ref(route.query.paper_id as string)
const type = $ref(parseInt(route.query.type as string))

// 所有试题
const questionList = $(inject<PaperQuestionType[]>('questionList'))

// 试题索引
let questionIndex = $ref<number>(0)
provide('questionIndex', $$(questionIndex))
watchEffect(() => {
  if (route.query.index) {
    questionIndex = parseInt(route.query.index as string) || 0
  }
})

// 试题数量
const questionLength = $computed(() => {
  return questionList.length
})
// 当前试题
const currentQuestion = $computed(() => {
  return questionList[questionIndex] || {}
})
// 提交中
let submitLoading = $ref<boolean>(false)
// 是否禁用
const disabled = $computed(() => {
  return props.status !== 1 || submitLoading
})
provide('disabled', $$(disabled))

// 上一题
function handlePrev() {
  if (questionIndex < 1) return
  questionIndex--
}
// 下一题
function handleNext() {
  if (questionIndex === questionLength - 1) return
  questionIndex++
}
// 提交
function handleSubmit() {
  // 未作答的数量
  const unansweredNum = questionList.reduce((result, item) => {
    if (item.children && item.children.length) {
      item.children.forEach(item => {
        !item.user_answer && result++
      })
    } else {
      !item.user_answer && result++
    }
    return result
  }, 0)

  if (unansweredNum) {
    ElMessageBox.confirm(`您还有${unansweredNum}道题没有作答`, '请确认', {
      confirmButtonText: '确认提交',
      cancelButtonText: '继续作答',
      type: 'warning'
    }).then(() => {
      handleSubmitPaper()
    })
  } else {
    handleSubmitPaper()
  }
}
// 提交试卷
function handleSubmitPaper() {
  submitLoading = true
  clearInterval(timer)
  submitPaper({
    course_id: courseId,
    semester_id: semesterId,
    paper_id: paperId,
    type,
    question: JSON.stringify(genSubmitQuestion(questionList))
  })
    .then(() => {
      ElMessage.success('提交成功')
      emit('update')
    })
    .catch(() => {
      submitLoading = false
    })
  // 日志上送
  log.upload({
    event: 'paper_event',
    action: 'stu_submit_paper_action',
    data: { course_id: courseId, paper_id: paperId, section_id: 0, commit_time: Math.floor(Date.now() / 1000) }
  })
}
// 提交缓存试卷
function handleSubmitCachePaper() {
  if (disabled) return
  cachePaper({
    course_id: courseId,
    semester_id: semesterId,
    paper_id: paperId,
    type,
    question: JSON.stringify(genSubmitQuestion(questionList))
  })
}
const timer = setInterval(handleSubmitCachePaper, 5000)
onUnmounted(() => {
  clearInterval(timer)
})
// 生成提交试卷的数据
function genSubmitQuestion(questionList: PaperQuestionType[]) {
  return questionList.map(question => {
    const userAnswer = question.user_answer ? question.user_answer.split(',') : []
    const options = question.question_options.map(item => {
      return { ...item, user_checked: userAnswer.includes(item.id) }
    })
    if (question.children && question.children.length) {
      question.children = genSubmitQuestion(question.children)
    }
    return { ...question, question_options: options }
  })
}
</script>

<template>
  <div class="course-exam-card">
    <div class="course-exam-card-hd">
      <router-link :to="`/course/view?course_id=${courseId}&semester_id=${semesterId}`">
        <el-button :icon="ArrowLeftBold" circle></el-button>
      </router-link>
      <div class="title">{{ title }}</div>
    </div>
    <div class="course-exam-card-bd">
      <div class="course-exam-left">
        <div class="course-exam-scroll">
          <CourseExamQuestion :question="currentQuestion" :status="status" :index="questionIndex + 1" v-if="questionLength">
            <template #index>{{ questionIndex + 1 }}/{{ questionLength }}</template>
          </CourseExamQuestion>
        </div>
        <div class="course-exam-buttons">
          <el-button size="large" :disabled="questionIndex === 0" @click="handlePrev">上一题</el-button>
          <el-button size="large" :disabled="questionIndex >= questionLength - 1" @click="handleNext"> 下一题 </el-button>
        </div>
      </div>
      <div class="course-exam-right">
        <div class="course-exam-scroll">
          <CourseExamQuestionNumbers :index="questionIndex" :status="status" />
        </div>
        <div class="course-exam-buttons">
          <el-button size="large" type="primary" auto-insert-space :disabled="disabled" @click="handleSubmit" style="width: 100%">
            {{ submitButtonText }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.course-exam-card {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: calc(100vh - 105px);
  min-height: 600px;
  background-color: #fff;
  border-radius: 6px;
  overflow: hidden;
}
.course-exam-card-hd {
  border-bottom: 1px solid #ccc;
  height: 0.8rem;
  background: #ffffff;
  display: flex;
  align-items: center;
  padding-left: 0.4rem;
  .title {
    padding-left: 0.2rem;
    font-size: 0.24rem;
    font-weight: bold;
    color: #222222;
    line-height: 0.8rem;
  }
  .right {
    width: 260px;
    margin-left: auto;
    display: flex;
    justify-content: space-around;
    align-items: center;
    .count {
      font-size: 18px;
      font-weight: bold;
      color: #222222;
    }
  }
}
.course-exam-card-bd {
  flex: 1;
  display: flex;
  overflow: hidden;
}
.course-exam-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  .course-exam-scroll {
    padding: 0 0.4rem;
  }
  .course-exam-buttons {
    padding: 0.2rem 0.4rem;
    border-top: 1px solid #ccc;
  }
}
.course-exam-right {
  display: flex;
  flex-direction: column;
  border-left: 1px solid #ccc;
  position: relative;
  width: 220px;
  background: #fff;
  padding: 0 0.2rem;
}
.course-exam-scroll {
  flex: 1;
  overflow-x: hidden;
  overflow-y: auto;
}
.course-exam-buttons {
  padding: 0.2rem 0;
}
.is-h5 {
  .course-exam-right {
    width: 80px;
  }
}
</style>
