<script setup lang="ts">
import type { DomMarkingData } from '../../composables/renderer/useMarkingDom'
import type { ExamStudentMarkingQuestionResponse } from '@/api'
import { markingSettings } from '../../composables/useMarkingSettings'
import QuestionRenderer from './QuestionRenderer.vue'

interface Props {
  imageSize: number
  questionData: ExamStudentMarkingQuestionResponse[]
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'marking-change': [questionIndex: number, imageIndex: number, data: DomMarkingData]
}>()

const scale = defineModel<number>('scale', { default: 1.0 })

// 转换为渲染数据
const questionDataList = computed(() => {
  if (!props.questionData?.length)
    return []

  return props.questionData.map((item, index) => ({
    id: `question_${item.tpl_question_id || index}_${item.scan_info_id}_${index}`,
    title: `${item.question_major || ''}${item.question_minor || ''}`,
    fullScore: item.full_score || 0,
    imageUrls: item.image_urls || [],
  }))
})

/**
 * 处理标记变化
 */
function handleMarkingChange(questionIndex: number, imageIndex: number, data: DomMarkingData) {
  emit('marking-change', questionIndex, imageIndex, data)
}
</script>

<template>
  <scroll-view
    scroll-y
    class="h-full w-full"
    :style="{ paddingBottom: '96rpx' }"
  >
    <!-- 题目列表 -->
    <view
      class="flex flex-col"
      :class="{
        'items-start': markingSettings.imagePosition === 'left',
        'items-center': markingSettings.imagePosition === 'center',
        'items-end': markingSettings.imagePosition === 'right',
      }"
      :style="{ gap: '24px', padding: '12px' }"
    >
      <QuestionRenderer
        v-for="(question, questionIndex) in questionDataList"
        :key="question.id"
        :question="question"
        :question-index="questionIndex"
        :scale="scale"
        :image-layout="markingSettings.imageLayout"
        :show-toolbar="markingSettings.showTraceToolbar"
        :initial-marking-data="
          questionData[questionIndex].remark
            ? JSON.parse(questionData[questionIndex].remark)
            : undefined
        "
        @marking-change="(imageIndex, data) => handleMarkingChange(questionIndex, imageIndex, data)"
      />
    </view>
  </scroll-view>
</template>
