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

<script lang="ts" setup>
import { useQuery } from '@tanstack/vue-query'
import dayjs from 'dayjs'
import { computed, 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 { 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>(1) // 默认按打分从小到大

// 获取历史分数选项
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 currentPage = ref(1)
const pageSize = ref(20)

const {
  data: historyData,
  isLoading: isLoadingHistory,
  error: historyError,
  refetch: refetchHistory,
} = useQuery({
  queryKey: ['review-history', taskId, currentPage, selectedScore, selectedOrderBy, useUserId()],
  queryFn: () => examMarkingTaskApi.historyDetail(
    taskId.value!,
    {
      page: currentPage.value,
      page_size: pageSize.value,
      is_review: true,
      history_score: selectedScore.value,
      order_by: selectedOrderBy.value,
    },
  ),
  enabled: enableQuery,
})

// 历史记录列表
const historyList = computed(() => historyData.value?.list || [])
const totalCount = computed(() => historyData.value?.total || 0)

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

// 处理排序变化
function handleOrderChange(orderBy: number) {
  console.log('排序变化:', orderBy)
  selectedOrderBy.value = orderBy
  currentPage.value = 1 // 重置到第一页
}

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

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

// 处理图片点击编辑分数
async function handleImageClick(record: any) {
  try {
    const result = await scoreEditDialogRef.value?.open({
      currentScore: record.score,
      recordTask: record,
    })

    if (result) {
      // 刷新历史记录
      await refetchHistory()
      uni.showToast({
        title: '分数修改成功',
        icon: 'success',
      })
    }
  }
  catch (error) {
    if (error !== 'cancel') {
      console.error('修改分数失败:', error)
    }
  }
}

// 加载更多
function loadMore() {
  if (historyData.value?.has_more) {
    currentPage.value += 1
  }
}

// 刷新数据
function handleRefresh() {
  currentPage.value = 1
  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 in historyList"
          :key="record.id"
          class="history-item mb-4 rounded-3 bg-white p-4 shadow-sm"
          @click="handleImageClick(record)"
        >
          <!-- 头部信息 -->
          <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"
            />
            <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="historyData?.has_more" class="load-more py-4">
          <wd-button
            type="primary"
            size="small"
            block
            @click="loadMore"
          >
            加载更多
          </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>
