<!-- 阅卷布局组件 -->
<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
  currentQuestionFullScore?: number
  currentQuestionFinalScore?: 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,
  currentQuestionFullScore: 0,
  currentQuestionFinalScore: 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-100vh w-100vw flex flex-grow flex-col bg-gray-100">
    <!-- 顶部导航栏 -->
    <view class="z-10 h-56px flex flex-shrink-0 items-center border-b border-slate-100 bg-white px-16px shadow-sm">
      <!-- 左侧返回按钮 -->
      <view class="mr-16px flex items-center justify-center">
        <view
          class="size-36px flex cursor-pointer items-center justify-center rounded-full bg-slate-50 text-slate-600 transition-all active:scale-95 active:bg-slate-200 hover:bg-slate-100"
          @click="emit('goBack')"
        >
          <view class="i-carbon-arrow-left size-20px" />
        </view>
      </view>

      <!-- 中间题号信息 -->
      <view class="flex flex-1 flex-col justify-center">
        <view class="flex items-baseline gap-2">
          <text class="text-18px text-slate-800 font-bold leading-none">
            {{ isViewingHistory ? historyModeText : `${currentTaskSubmit}/${totalQuestions}` }}
          </text>
          <text class="text-12px text-slate-400 leading-none">
            题号
          </text>
        </view>
      </view>

      <!-- 右侧操作按钮组 -->
      <view class="flex items-center gap-12px">
        <view
          v-for="(btn, idx) in [
            { text: '设置', icon: 'i-carbon-settings', action: 'openScoreSettings' },
            { text: '均分', icon: 'i-carbon-chart-bar', action: 'viewAvgScore' },
            { text: '答案', icon: 'i-carbon-document', action: 'viewAnswer' },
          ]"
          :key="idx"
          class="flex flex-col cursor-pointer items-center justify-center gap-2px rounded-lg px-8px py-4px transition-colors active:bg-slate-100 hover:bg-slate-50"
          @click="emit(btn.action as any)"
        >
          <view :class="btn.icon" class="text-18px text-slate-600" />
          <text class="text-10px text-slate-500">{{ btn.text }}</text>
        </view>

        <view class="mx-4px h-24px w-1px bg-slate-200" />

        <view
          class="size-36px flex cursor-pointer items-center justify-center rounded-full bg-slate-50 text-slate-600 transition-all active:scale-95 active:bg-slate-200 hover:bg-slate-100"
          @click="emit('toggleFullscreen')"
        >
          <view class="i-carbon-image-search size-22px" />
        </view>
        <view
          class="size-36px flex cursor-pointer items-center justify-center rounded-full bg-slate-50 text-slate-600 transition-all active:scale-95 active:bg-slate-200 hover:bg-slate-100"
          @click="emit('toggleOrientation')"
        >
          <view class="i-carbon:mobile-view-orientation size-22px" />
        </view>
      </view>
    </view>

    <!-- 内容区域 - 左右分栏 -->
    <view class="flex flex-1 overflow-hidden">
      <!-- 左侧打分信息面板 -->
      <view class="z-5 w-72px flex flex-col items-center border-r border-slate-100 bg-white py-16px shadow-sm">
        <view class="w-full flex flex-col items-center gap-12px">
          <view class="flex flex-col items-center gap-2px">
            <text class="text-10px text-slate-400">满分</text>
            <text class="text-14px text-slate-600 font-semibold font-mono">{{ formatScore(currentQuestionFullScore) }}</text>
          </view>

          <view class="h-1px w-32px bg-slate-100" />

          <view class="flex flex-col items-center gap-2px">
            <text class="text-10px text-slate-400">得分</text>
            <text class="text-20px text-blue-600 font-bold font-mono">
              {{ isViewingHistory ? formatScore(currentQuestionFinalScore) : '--' }}
            </text>
          </view>
        </view>
      </view>

      <!-- 中间图片区域 -->
      <view class="relative flex-1 overflow-hidden bg-slate-50">
        <slot name="content" :current-question="currentQuestion" />
      </view>

      <!-- 右侧打分区域 -->
      <slot name="scoring" />
    </view>
  </view>

  <!-- 竖屏布局 -->
  <view v-else class="h-100vh w-100vw flex flex-grow flex-col bg-slate-50">
    <!-- 顶部导航栏 -->
    <view class="z-10 flex flex-col bg-white shadow-sm">
      <view class="h-44px flex items-center justify-between px-16px">
        <view class="flex items-center gap-8px">
          <view
            class="size-32px flex cursor-pointer items-center justify-center rounded-full bg-slate-50 text-slate-600 active:bg-slate-100"
            @click="emit('goBack')"
          >
            <view class="i-carbon-arrow-left size-18px" />
          </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 class="flex items-center gap-4px rounded-full bg-slate-50 px-12px py-4px active:bg-slate-100">
              <text class="text-14px text-slate-800 font-bold">
                {{ currentQuestion?.question_major }}.{{ currentQuestion?.question_minor }}
              </text>
              <view class="i-carbon-chevron-down text-12px text-slate-400" />
            </view>
          </wd-picker>
        </view>

        <view class="flex items-center gap-2">
          <!-- 题目序号 -->
          <text class="mr-2 text-14px text-slate-600 font-medium">
            {{ currentTaskSubmit }}/{{ totalQuestions }}
          </text>

          <view class="flex gap-8px">
            <view
              class="size-32px flex cursor-pointer items-center justify-center rounded-full bg-slate-50 text-slate-600 active:bg-slate-100"
              @click="emit('toggleFullscreen')"
            >
              <view class="i-carbon-image-search size-18px" />
            </view>
            <view
              class="size-32px flex cursor-pointer items-center justify-center rounded-full bg-slate-50 text-slate-600 active:bg-slate-100"
              @click="emit('toggleOrientation')"
            >
              <view class="i-carbon:mobile-view-orientation size-18px" />
            </view>
          </view>
        </view>
      </view>

      <!-- 二层信息栏 -->
      <view class="h-36px flex items-center justify-between border-t border-slate-100 bg-slate-50 px-16px">
        <view class="flex items-baseline gap-2">
          <text class="text-12px text-slate-500">满分</text>
          <text class="text-12px text-slate-800 font-bold font-mono">{{ formatScore(currentQuestionFullScore) }}</text>
          <div class="mx-2 h-10px w-1px bg-slate-300" />
          <text class="text-12px text-slate-500">得分</text>
          <text class="text-16px text-blue-600 font-bold font-mono">
            {{ isViewingHistory ? formatScore(currentQuestionFinalScore) : '--' }}
          </text>
        </view>

        <view class="flex items-center gap-16px">
          <text
            v-for="(action, idx) in [
              { t: '设置', a: 'openScoreSettings' },
              { t: '均分', a: 'viewAvgScore' },
              { t: '答案', a: 'viewAnswer' },
            ]"
            :key="idx"
            class="text-12px text-slate-500 active:text-blue-600"
            @click="emit(action.a as any)"
          >
            {{ action.t }}
          </text>
        </view>
      </view>
    </view>

    <!-- 作答区域和打分区域 - 左右分栏 -->
    <view class="relative flex flex-1 overflow-hidden">
      <!-- 左侧图片区域 -->
      <view class="relative flex-1 overflow-hidden bg-slate-50">
        <slot name="content" :current-question="currentQuestion" />
      </view>

      <!-- 右侧打分区域 -->
      <slot name="scoring" />
    </view>
  </view>
</template>

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

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