<!-- 阅卷布局组件 -->
<script lang="ts" setup>
import type { ExamQuestionWithTasksResponse } from '@/api'
import { computed, ref, watch } from 'vue'
import { useMarkingHistory } from '@/composables/marking/useMarkingHistory'

interface Props {
  isLandscape: boolean
  currentQuestionIndex: number
  totalQuestions: number
  currentTaskSubmit: number
  questions: ExamQuestionWithTasksResponse[]
  myScore?: number
  avgScore?: number
  isViewingHistory?: boolean
  canGoPrev?: boolean
  canGoNext?: boolean
  historyModeText?: string
  taskId?: number
}

interface Emits {
  (e: 'goBack'): void
  (e: 'selectQuestion', index: number): void
  (e: 'openScoreSettings'): void
  (e: 'viewAvgScore'): void
  (e: 'viewAnswer'): void
  (e: 'toggleOrientation'): void
  (e: 'toggleFullscreen'): void
  (e: 'prevQuestion'): void
  (e: 'nextQuestion'): void
}

const props = withDefaults(defineProps<Props>(), {
  myScore: 0,
  avgScore: 0,
  isViewingHistory: false,
  canGoPrev: false,
  canGoNext: false,
  historyModeText: '',
  taskId: 0,
})

const emit = defineEmits<Emits>()

// 获取历史记录管理
const markingHistory = useMarkingHistory()
const currentHistoryPage = ref(1)
const { data: historyPageData, isLoading: isLoadingHistory } = markingHistory.useHistoryPage(
  computed(() => currentHistoryPage.value),
)

// 监听 taskId 变化，重置历史记录页面
watch(() => props.taskId, () => {
  if (props.taskId) {
    currentHistoryPage.value = 1
  }
})

// 当前题目信息
const currentQuestion = computed(() => props.questions[props.currentQuestionIndex])

// 题目选择器选项
const questionPickerColumns = computed(() => [
  props.questions.map((q, index) => ({
    label: `${q.question_major}.${q.question_minor}`,
    value: index,
  })),
])

// 格式化分数，保留最少的小数位
function formatScore(score: number): string {
  if (score === 0)
    return '0'
  if (score % 1 === 0)
    return score.toString() // 整数不显示小数

  // 最多保留2位小数，去掉尾部的0
  const formatted = score.toFixed(2)
  return formatted.replace(/\.?0+$/, '')
}

// 历史记录列表（最新的在顶部）
const historyList = computed(() => {
  if (!historyPageData.value?.list)
    return []
  // 不反转，后端返回的数据最新的在前，直接使用
  return historyPageData.value.list
})

// 跳转到历史记录
async function goToHistoryIndex(index: number) {
  // 列表索引转全局索引
  // 列表 index 0 是最新的，对应全局索引 total - 1
  // 列表 index n-1 是最旧的，对应全局索引 0
  const total = markingHistory.totalHistoryCount.value
  const globalIndex = total - 1 - index
  await markingHistory.goToHistoryIndex(globalIndex)
}

// 当前选中的历史记录索引（用于高亮）
const currentHistoryIndexInList = computed(() => {
  if (!props.isViewingHistory)
    return -1
  const currentIndex = markingHistory.currentHistoryIndex.value
  const total = markingHistory.totalHistoryCount.value
  // 全局索引转列表索引：全局索引 n-1（最新）对应列表索引 0
  return total - 1 - currentIndex
})
</script>

<template>
  <!-- 横屏布局 -->
  <view v-if="isLandscape" class="h-0 w-100vw flex flex-grow flex-col bg-gray-100">
    <!-- 顶部导航栏 -->
    <view class="h-48px flex items-center border-b bg-white px-16px shadow-sm">
      <!-- 左侧返回按钮 -->
      <view class="w-64px flex justify-start border-r">
        <view
          class="size-40px flex cursor-pointer items-center justify-center rounded transition-colors hover:bg-gray-100"
          @click="emit('goBack')"
        >
          <view class="i-carbon-arrow-left size-20px text-gray-700" />
        </view>
      </view>

      <!-- 右侧导航栏 -->
      <view class="flex flex-1 items-center justify-between pl-16px">
        <!-- 题号信息 -->
        <view class="mr-16px flex items-center">
          <text class="text-16px text-gray-800 font-medium">
            {{ isViewingHistory ? historyModeText : `${currentTaskSubmit + 1}/${totalQuestions}` }}
          </text>
        </view>

        <!-- 操作按钮组 -->
        <view class="flex items-center gap-16px text-14px">
          <view
            class="cursor-pointer text-gray-700 transition-colors hover:text-blue-500"
            @click="emit('openScoreSettings')"
          >
            打分设置
          </view>
          <view
            class="cursor-pointer text-gray-700 transition-colors hover:text-blue-500"
            @click="emit('viewAvgScore')"
          >
            查看均分
          </view>
          <view
            class="cursor-pointer text-gray-700 transition-colors hover:text-blue-500"
            @click="emit('viewAnswer')"
          >
            查看答案
          </view>
          <view
            class="size-32px flex cursor-pointer items-center justify-center rounded transition-colors hover:bg-gray-100"
            @click="emit('toggleOrientation')"
          >
            <view class="i-carbon:mobile-view-orientation size-18px text-gray-700" />
          </view>
          <view
            class="size-32px flex cursor-pointer items-center justify-center rounded transition-colors hover:bg-gray-100"
            @click="emit('toggleFullscreen')"
          >
            <view
              class="i-carbon-image-search size-18px text-gray-700"
            />
          </view>
        </view>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="h-0 flex flex-1">
      <!-- 左侧历史记录面板 -->
      <view class="w-80px flex flex-col overflow-auto border-r border-gray-200 bg-white">
        <!-- 历史记录列表 -->
        <view
          v-for="(record, index) in historyList"
          :key="record.id"
          class="flex flex-col cursor-pointer items-center justify-center border-b border-gray-100 px-4px py-8px text-10px transition-colors"
          :class="[
            currentHistoryIndexInList === index
              ? 'bg-blue-500 text-white'
              : 'bg-white text-gray-700 hover:bg-gray-50',
          ]"
          @click="goToHistoryIndex(index)"
        >
          <view class="mb-2px font-medium">
            {{ record.question_major }}.{{ record.question_minor }}
          </view>
          <view class="text-12px font-semibold">
            {{ formatScore(record.score) }}/{{ formatScore(record.full_score) }}
          </view>
        </view>
      </view>

      <!-- 右侧作答区域 -->
      <view class="relative h-full flex-1 overflow-auto bg-green-200">
        <!-- 左右箭头按钮 -->
        <view
          class="arrow-btn-landscape fixed z-100 size-32px flex cursor-pointer items-center justify-center rounded transition-colors"
          :class="canGoPrev ? 'bg-gray-100 hover:bg-gray-200' : 'bg-gray-50 opacity-50 cursor-not-allowed'"
          @click="canGoPrev && emit('prevQuestion')"
        >
          <view class="i-carbon-chevron-left size-16px text-gray-700" />
        </view>
        <view
          class="arrow-btn-landscape fixed right-0 z-100 size-32px flex cursor-pointer items-center justify-center rounded transition-colors"
          :class="canGoNext ? 'bg-gray-100 hover:bg-gray-200' : 'bg-gray-50 opacity-50 cursor-not-allowed'"
          @click="canGoNext && emit('nextQuestion')"
        >
          <view class="i-carbon-chevron-right size-16px text-gray-700" />
        </view>
        <slot name="content" :current-question="currentQuestion" />
      </view>
    </view>
  </view>

  <!-- 竖屏布局 -->
  <view v-else class="h-0 w-100vw flex flex-grow flex-col bg-gray-100">
    <!-- 顶部导航栏 -->
    <view class="h-12 flex items-center bg-white px-4 py-2 shadow-sm">
      <!-- 左侧 -->
      <view class="flex items-center gap-3">
        <view
          class="size-8 flex cursor-pointer items-center justify-center rounded transition-colors hover:bg-gray-100"
          @click="emit('goBack')"
        >
          <view class="i-carbon-arrow-left size-5 text-gray-700" />
        </view>

        <!-- 题目选择器弹窗 -->
        <wd-picker
          :model-value="currentQuestionIndex"
          :columns="questionPickerColumns"
          :value="String(currentQuestionIndex)"
          :title="`${currentQuestion?.question_major}.${currentQuestion?.question_minor}`"
          @confirm="({ value }) => emit('selectQuestion', Number(value))"
        />
      </view>

      <!-- 右侧分数信息 -->
      <view class="flex flex-1 justify-end">
        <text class="text-sm text-gray-600">
          我的均分/本题均分: {{ formatScore(myScore) }}/{{ formatScore(avgScore) }}
        </text>
      </view>
    </view>

    <!-- 二层导航栏 -->
    <view class="h-12 flex items-center border-t border-gray-200 bg-white px-4 py-2">
      <!-- 题号信息 -->
      <view class="flex items-center gap-4">
        <text v-if="!isViewingHistory" class="text-base text-gray-800 font-medium">
          {{ Math.min(totalQuestions, currentTaskSubmit + 1) }}/{{ totalQuestions }}
        </text>
        <text v-else class="text-base text-gray-800 font-medium">
          {{ historyModeText }}
        </text>
      </view>

      <!-- 操作按钮组 -->
      <view class="flex flex-1 items-center justify-end gap-3">
        <view
          class="cursor-pointer text-sm text-gray-700 transition-colors hover:text-blue-500"
          @click="emit('openScoreSettings')"
        >
          打分设置
        </view>
        <view
          class="cursor-pointer text-sm text-gray-700 transition-colors hover:text-blue-500"
          @click="emit('viewAvgScore')"
        >
          查看均分
        </view>
        <view
          class="cursor-pointer text-sm text-gray-700 transition-colors hover:text-blue-500"
          @click="emit('viewAnswer')"
        >
          查看答案
        </view>
        <view
          class="size-28px flex cursor-pointer items-center justify-center rounded transition-colors hover:bg-gray-100"
          @click="emit('toggleOrientation')"
        >
          <view class="i-carbon:mobile-view-orientation size-16px text-gray-700" />
        </view>
        <view
          class="size-28px flex cursor-pointer items-center justify-center rounded transition-colors hover:bg-gray-100"
          @click="emit('toggleFullscreen')"
        >
          <view
            class="i-carbon-image-search size-16px text-gray-700"
          />
        </view>
      </view>
    </view>

    <!-- 作答区域 -->
    <view class="relative flex-1 bg-green-200">
      <!-- 左右箭头按钮 -->
      <view
        class="arrow-btn-portrait fixed left-2 z-100 size-28px flex cursor-pointer items-center justify-center rounded transition-colors"
        :class="canGoPrev ? 'bg-gray-100 hover:bg-gray-200' : 'bg-gray-50 opacity-50 cursor-not-allowed'"
        @click="canGoPrev && emit('prevQuestion')"
      >
        <view class="i-carbon-chevron-left size-16px text-gray-700" />
      </view>
      <view
        class="arrow-btn-portrait fixed right-2 z-100 size-28px flex cursor-pointer items-center justify-center rounded transition-colors"
        :class="canGoNext ? 'bg-gray-100 hover:bg-gray-200' : 'bg-gray-50 opacity-50 cursor-not-allowed'"
        @click="canGoNext && emit('nextQuestion')"
      >
        <view class="i-carbon-chevron-right size-16px text-gray-700" />
      </view>

      <slot name="content" :current-question="currentQuestion" />
    </view>
  </view>
</template>

<style scoped lang="scss">
.arrow-btn-landscape {
  top: 50%;
  transform: translateY(-50%);
}

.arrow-btn-portrait {
  top: 50%;
  transform: translateY(-50%);
}
</style>
