<!-- 回评页面 -->
<route lang="jsonc">
{
  "style": {
    "navigationBarTitleText": "回评"
  }
}
</route>

<script lang="ts" setup>
import { useInfiniteQuery, useQuery } from '@tanstack/vue-query'
import { whenever } from '@vueuse/core'
import dayjs from 'dayjs'
import { computed, nextTick, ref } from 'vue'
import { examMarkingTaskApi } from '@/api'
import ReviewHeader from '@/components/marking/review/ReviewHeader.vue'
import ReviewImageRenderer from '@/components/marking/review/ReviewImageRenderer.vue'
import ScoreEditDialog from '@/components/marking/review/ScoreEditDialog.vue'
import { setReviewQuestion } from '@/composables/marking/ReviewMarkingContext'
import { useUserId } from '@/composables/useUserId'

defineOptions({
  name: 'MarkingReviewPage',
})

// 获取路由参数
const taskId = ref<number>()
const questionId = ref<number>()
const examId = ref<number>()
const subjectId = ref<number>()

const enableQuery = computed(() => !!taskId.value)

// 页面加载时获取参数
onLoad((options) => {
  taskId.value = Number(options.taskId)
  questionId.value = Number(options.questionId)
  examId.value = Number(options.examId)
  subjectId.value = Number(options.subjectId)
  console.log('回评页面参数:', { taskId: taskId.value, questionId: questionId.value })
})

// 筛选和排序状态
const selectedScore = ref<number>()
const selectedOrderBy = ref<number>(4) // 默认按打分从小到大

// 获取历史分数选项
const {
  data: historyScoreOptions,
  isLoading: isLoadingScoreOptions,
} = useQuery({
  queryKey: ['review-history-score', taskId, useUserId()],
  queryFn: () => examMarkingTaskApi.reviewHistoryScoreCreate({
    task_id: taskId.value!,
  }),
  enabled: enableQuery,
  select: data => data?.history_scores || [],
})

// 每页数量
const pageSize = 20

// 使用 useInfiniteQuery 获取历史记录数据
const {
  data: historyData,
  isLoading: isLoadingHistory,
  error: historyError,
  fetchNextPage,
  hasNextPage,
  isFetchingNextPage,
  refetch: refetchHistory,
} = useInfiniteQuery({
  queryKey: ['review-history-infinite', taskId, selectedScore, selectedOrderBy, useUserId()],
  queryFn: ({ pageParam = 1 }) => examMarkingTaskApi.historyDetail(
    taskId.value!,
    {
      page: pageParam,
      page_size: pageSize,
      is_review: true,
      history_score: selectedScore.value,
      order_by: selectedOrderBy.value,
    },
  ),
  enabled: enableQuery,
  initialPageParam: 1,
  getNextPageParam: (lastPage, allPages, lastPageParam) => {
    // 如果还有更多数据，返回下一页页码
    if (lastPage?.has_more) {
      return lastPageParam + 1
    }
    // 没有更多数据时返回 undefined
    return undefined
  },
})

// 历史记录列表 - 合并所有页面的数据
const historyList = computed(() => {
  if (!historyData.value?.pages) {
    return []
  }
  return historyData.value.pages.flatMap(page => page?.list || [])
})

// 总数（从第一页获取）
const totalCount = computed(() => historyData.value?.pages?.[0]?.total || 0)

// 处理分数筛选变化
function handleScoreChange(score?: number) {
  console.log('分数筛选变化:', score)
  selectedScore.value = score
  // 筛选变化时，useInfiniteQuery 会自动重置到第一页
}

// 处理排序变化
function handleOrderChange(orderBy: number) {
  console.log('排序变化:', orderBy)
  selectedOrderBy.value = orderBy
  // 排序变化时，useInfiniteQuery 会自动重置到第一页
}

// 返回上一页
function goBack() {
  uni.navigateBack()
}

// 分数编辑对话框
const scoreEditDialogRef = ref<InstanceType<typeof ScoreEditDialog>>()

// 容器宽度
// 默认给一个预估值，避免首次渲染时宽度为0导致缩放计算错误
// 预估逻辑：屏幕宽度 - 页面padding(32) - 卡片padding(32) - 内部预留(32)
const systemInfo = uni.getSystemInfoSync()
const containerWidth = ref(systemInfo.windowWidth - 96)

// 获取容器宽度
function updateContainerWidth() {
  const query = uni.createSelectorQuery()
  query.select('.image-container').boundingClientRect((data) => {
    if (data && !Array.isArray(data) && data.width > 0) {
      // 减去padding和边框，获取实际可用宽度
      containerWidth.value = data.width - 32 // 32 = padding 16px * 2
      console.log('[Review] Container width:', containerWidth.value)
    }
  }).exec()
}

whenever(() => historyData.value?.pages?.length, () => {
  // 使用 nextTick 确保 DOM 已更新
  nextTick(() => {
    // 稍微延迟以确保布局稳定
    setTimeout(updateContainerWidth, 200)
  })
}, { immediate: true })

let lastQuestionIndex = -1
// 处理图片点击进入回评阅卷页
function handleImageClick(record: any, index: number) {
  // 构造题目数据
  const questionData = {
    ...record,
    // 构造 tasks 对象，确保 grading 页面能正确识别任务
    tasks: {
      initial: {
        id: record.task_id,
        question_id: record.question_id,
        task_type: 'initial',
      },
    },
    // 确保有 standard_answer 字段，防止报错
    standard_answer: record.standard_answer || '',
    // 映射分数
    final_score: record.score,
  }

  // 设置回评题目
  setReviewQuestion(questionData)
  lastQuestionIndex = index

  // 跳转到阅卷页（回评模式）
  uni.navigateTo({
    url: `/pages/marking/grading?taskId=${record.task_id}&questionId=${record.question_id}&examId=${examId.value}&subjectId=${subjectId.value}&type=single&taskType=initial&mode=review`,
  })
}

const refreshKey = ref(0)
onShow(async () => {
  if (lastQuestionIndex !== -1) {
    await refetchHistory()
    refreshKey.value += 1
  }
})

// 加载更多
function loadMore() {
  if (hasNextPage.value && !isFetchingNextPage.value) {
    fetchNextPage()
  }
}

// 刷新数据
function handleRefresh() {
  refetchHistory()
}
</script>

<template>
  <view class="review-page bg-gray-50">
    <!-- 顶部筛选栏 -->
    <ReviewHeader
      :history-score-options="historyScoreOptions || []"
      :is-loading-options="isLoadingScoreOptions"
      @score-change="handleScoreChange"
      @order-change="handleOrderChange"
      @go-back="goBack"
      @refresh="handleRefresh"
    />

    <!-- 主体内容区 -->
    <view class="content-area flex-1 p-4">
      <!-- 加载状态 -->
      <view v-if="isLoadingHistory" class="loading-container flex-center h-50">
        <wd-loading size="24" />
        <text class="ml-2 text-sm text-gray-600">加载中...</text>
      </view>

      <!-- 错误状态 -->
      <view v-else-if="historyError" class="error-container flex-center h-50">
        <view class="text-center">
          <text class="mb-3 block text-sm text-gray-600">加载失败</text>
          <wd-button type="primary" size="small" @click="handleRefresh">
            重试
          </wd-button>
        </view>
      </view>

      <!-- 历史记录列表 -->
      <view v-else-if="historyList.length > 0" class="history-list">
        <view
          v-for="(record, index) in historyList"
          :key="`${record.id}_${refreshKey}`"
          class="history-item mb-4 rounded-3 bg-white p-4 shadow-sm"
          @click="handleImageClick(record, index)"
        >
          <!-- 头部信息 -->
          <view class="item-header mb-3 flex items-center justify-between">
            <view class="score-info">
              <text class="score text-2xl text-red-600 font-bold">{{ record.score }}</text>
              <text class="total-score text-base text-gray-500">/ {{ record.full_score }}</text>
            </view>
            <view class="time-info text-right">
              <text class="time text-sm text-gray-500">{{ dayjs(record.created_time).format('YYYY-MM-DD HH:mm:ss') }}</text>
            </view>
          </view>

          <!-- 图片展示区 -->
          <view class="image-container">
            <ReviewImageRenderer
              v-if="record.image_urls?.length"
              :image-urls="record.image_urls"
              :marking-data="record.remark"
              :score="record.score"
              :full-score="record.full_score"
              :container-width="containerWidth"
            />
            <view v-else class="no-image flex-center h-32 rounded-2 bg-gray-100">
              <text class="text-gray-400">暂无图片</text>
            </view>
          </view>
        </view>

        <!-- 加载更多 -->
        <view v-if="hasNextPage" class="load-more py-4">
          <wd-button
            type="primary"
            size="small"
            block
            :loading="isFetchingNextPage"
            :disabled="isFetchingNextPage"
            @click="loadMore"
          >
            {{ isFetchingNextPage ? '加载中...' : '加载更多' }}
          </wd-button>
        </view>

        <!-- 没有更多数据 -->
        <view v-else-if="historyList.length > 0" class="no-more py-4 text-center">
          <text class="text-sm text-gray-400">没有更多数据了</text>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-else class="empty-state flex-center h-50">
        <view class="text-center">
          <view class="i-fluent:document-search-20-filled mb-4 size-20 text-gray-400" />
          <text class="text-sm text-gray-500">暂无历史记录</text>
          <text class="mt-2 block text-xs text-gray-400">请调整筛选条件</text>
        </view>
      </view>
    </view>

    <!-- 分数编辑对话框 -->
    <ScoreEditDialog ref="scoreEditDialogRef" />
  </view>
</template>

<style scoped>
.review-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.content-area {
  flex: 1;
}

.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.history-item {
  transition: all 0.2s ease;
}

.history-item:active {
  transform: scale(0.98);
  background-color: #f8f9fa;
}

.score {
  line-height: 1;
}

.total-score {
  line-height: 1;
}
</style>
