<script setup lang="ts">
import questionExplainApi from '@/api/subject/questionExplain'
import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'
import type { IQuestion } from '@/types/question'
import { $XXL } from '@/utils'
import hud from '@/utils/hud'
import { useTeacherExplain } from '@/hooks'

defineOptions({
  name: 'QuestionExplain',
})

const route = useRoute()
const router = useRouter()
const pageLoading = ref(true)

interface ExplainQuestion extends IQuestion {
  unLook: boolean
  uploadLoading: boolean
  correctResult: boolean
}

const paperList = ref<ExplainQuestion[]>([])
const paperInfo = ref<any>({})
const activeIdx = ref(0)
let leaveFlag = false

// 讲解模式下禁止用户返回上一页，仅在收到停止讲解消息时允许离开
onBeforeRouteLeave((_to, _from, next) => {
  if (leaveFlag) return next()
  next(false)
})

// 监听 WebSocket 消息
const { onMessage } = useTeacherExplain()
const unregister = onMessage(data => {
  if (data.type === 'questionExplainStop') {
    let msg = data.msg
    if (typeof msg === 'string') {
      try {
        msg = JSON.parse(msg)
      } catch {
        return
      }
    }
    if (msg?.explaining === false) {
      hud.info('老师已结束讲解')
      leaveFlag = true
      router.push('/')
    }
  }

  // 收到 questionExplainStart 时，根据 questionId 切换到对应题目
  if (data.type === 'questionExplainStart') {
    let msg = data.msg
    if (typeof msg === 'string') {
      try {
        msg = JSON.parse(msg)
      } catch {
        return
      }
    }
    if (msg?.questionId && paperList.value.length) {
      const idx = paperList.value.findIndex(q => String(q.id) === String(msg.questionId))
      if (idx !== -1) {
        activeIdx.value = idx
        hud.info(`正在讲解第${idx + 1}题`)
      }
    }
  }
})

const title = computed(() => {
  const name = paperInfo.value?.paperName
  if (name) {
    return name.replace(/-\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/, '')
  }
  return '讲解'
})

async function init() {
  try {
    pageLoading.value = true
    const recordId = route.query.recordId as string
    if (!recordId) return

    const data = await questionExplainApi.getPaperDetailByReleaseRecordId(recordId)
    paperInfo.value = data
    paperList.value = data?.titleVoList || []

    if (paperList.value.length) {
      const questionId = route.query.questionId as string
      if (questionId) {
        const idx = paperList.value.findIndex(q => String(q.id) === String(questionId))
        activeIdx.value = idx !== -1 ? idx : 0
      }
    }
  } catch (err) {
    console.error('[QuestionExplain] init error', err)
  } finally {
    pageLoading.value = false
  }
}

function noopUpload() {}
function noopBeforeUpload() {
  return true
}

onMounted(async () => {
  $XXL.setScreenOn(1)
  await init()
})

onUnmounted(() => {
  unregister()
  paperList.value = []
  paperInfo.value = {}
})
</script>
<template>
  <div class="explain-page g-main-bg">
    <div class="top">
      <div></div>
    </div>
    <div v-if="!pageLoading" class="main">
      <div class="main-box">
        <div class="main-top">
          <div class="title" :data-content="title">
            {{ title }}
          </div>
        </div>
        <div class="book-box">
          <div class="book">
            <template v-if="paperList && paperList.length > 0 && paperList[activeIdx]">
              <Question
                :data="paperList[activeIdx]"
                :idx="activeIdx + 1"
                :total="paperList.length"
                resource-type=""
                :isDeadline="true"
                :reportFlag="1"
                :uploadFile="noopUpload"
                :beforeUpload="noopBeforeUpload"
                :explainMode="true"
              />
            </template>
          </div>
        </div>
        <div class="bottom">
          <div class="indicator">
            <div
              v-for="(i, idx) in paperList"
              :key="i.id || idx"
              :class="{
                'indicator-item': true,
                active: activeIdx === idx,
              }"
            >
              {{ idx + 1 }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <mj-loading v-else v-model="pageLoading" :fullscreen="true" text="正在加载讲解内容..." />
  </div>
</template>
<style scoped lang="scss">
.explain-page {
  position: relative;
  height: 100%;
  overflow: hidden;
  box-sizing: border-box;
  line-height: 1.5;

  .top {
    padding: 2.67vh 64px 0;
    position: relative;
    z-index: 1;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .main {
    box-sizing: border-box;
    padding: 0 32px;
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;

    &-top {
      margin-bottom: 1vh;
      display: flex;
      justify-content: center;
      padding: 0 140px;

      .title {
        color: #fff;
        text-shadow: 0 0.17vh 0.17vh rgba(0, 0, 0, 0.25);
        font-family: $font-special;
        font-size: 4vh;
        font-style: normal;
        font-weight: 400;
        line-height: 6vh;
        text-align: center;
        letter-spacing: 10px;
        @include font-stroke($font-color, 6px);
        @include single_ellipsis;
      }
    }

    &-box {
      position: relative;
      top: 3vh;
    }

    .book-box {
      position: relative;
      height: 80vh;
      padding-top: 1.25vh;
    }

    .book {
      box-sizing: border-box;
      position: relative;
      z-index: auto;
      height: 100%;
      padding-bottom: 5.83vh;
      flex-shrink: 0;
      border-radius: 3.33vh;
    }
  }

  .bottom {
    display: flex;
    align-items: center;
    width: 100%;
    padding: 0 32px;
    position: relative;
    z-index: 10;
    overflow: hidden;

    .indicator {
      flex: 1;
      min-width: 0;
      display: flex;
      overflow-x: auto;
      overflow-y: hidden;
      padding: 0.83vh 0;
      user-select: none;
      scrollbar-width: none;
      -ms-overflow-style: none;

      &::-webkit-scrollbar {
        display: none;
      }

      &-item {
        box-sizing: border-box;
        width: 6.67vh;
        height: 6.67vh;
        background: #bed5fe;
        border-radius: 50%;
        margin-right: 24px;
        color: $font-color;
        text-align: center;
        font-family: $font-special;
        font-size: 3.33vh;
        font-style: normal;
        font-weight: 400;
        line-height: 6.67vh;
        flex-shrink: 0;
        box-shadow: 0 0.33vh 0.33vh 0 rgba(0, 0, 0, 0.25);
        pointer-events: none;

        &:last-child {
          margin-right: 0;
        }

        &.active {
          background: #ebf1fd;
          border: 0.33vh solid #7eacfe;
          line-height: 6vh;
          color: #7eacfe;
        }
      }
    }
  }
}
</style>
