<script setup lang="ts">
/**
 * 试卷预览组件
 * 支持显示试卷信息、大题和小题
 */
import { onMounted, ref } from 'vue';

import { ElAlert, ElIcon } from 'element-plus';

// @ts-ignore
import { PaperCategoryTree } from '#/api/exam/paper/category';
// @ts-ignore
import { paperDetail } from '#/api/exam/paper/paper';
// @ts-ignore
import QuestionPreview from '#/components/question';
// @ts-ignore

interface Props {
  paperId: string; // 试卷编号
}

const props = withDefaults(defineProps<Props>(), {
  paperId: '',
});

// 试卷信息
const paperInfo = ref({
  paperName: '',
  categoryId: '',
  categoryName: '',
  paperDescription: '',
  totalScore: 0,
  questionCount: 0,
});

// 试卷大题数据
const bigQuestions = ref<any[]>([]);

// 试卷分类树
const paperCategoryTree = ref<any[]>([]);

// 加载状态
const loading = ref(true);

// 错误信息
const error = ref('');

/**
 * 获取试卷详情
 */
const getPaperDetail = async (id: string) => {
  try {
    loading.value = true;
    error.value = '';

    // 获取试卷详情
    const res: any = await paperDetail(+id);
    if (res) {
      // 保存试卷基本信息
      paperInfo.value = {
        paperName: res.paperName,
        categoryId: res.categoryId,
        categoryName: '', // 稍后从分类树中获取
        paperDescription: res.paperDescription || '',
        totalScore: res.totalScore,
        questionCount: res.questionCount,
      };

      // 解析大题数据
      bigQuestions.value = JSON.parse(res.bigQuestionNames || '[]').map(
        (item: any, index: number) => {
          const questions = (res.questions || [])
            .filter((q: any) => q.bigQuestionIndex === index)
            .map((q: any) => ({
              ...q.info,
              score: q.smallQuestionScore,
              sortOrder: q.sortOrder,
              drawType: q.drawType,
            }));

          return {
            title: item.name,
            score: item.score,
            num: item.num,
            questions,
          };
        },
      );

      // 获取分类名称
      getCategoryName(res.categoryId);
    }
  } catch (error_) {
    error.value = '获取试卷详情失败';
    console.error('获取试卷详情失败:', error_);
  } finally {
    loading.value = false;
  }
};

/**
 * 从分类树中获取分类名称
 */
const getCategoryName = (categoryId: string) => {
  const findCategory = (tree: any[], id: string): string => {
    for (const item of tree) {
      if (item.id === id) {
        return item.name;
      }
      if (item.children && item.children.length > 0) {
        const name = findCategory(item.children, id);
        if (name) {
          return name;
        }
      }
    }
    return '';
  };

  paperInfo.value.categoryName = findCategory(
    paperCategoryTree.value,
    categoryId,
  );
};

/**
 * 获取试卷分类树
 */
const getPaperCategoryTree = async () => {
  try {
    const res: any = await PaperCategoryTree();
    paperCategoryTree.value = res.rows || [];
  } catch (error_) {
    console.error('获取试卷分类树失败:', error_);
  }
};

// 组件挂载时获取数据
onMounted(async () => {
  // 先获取分类树
  await getPaperCategoryTree();
  // 再获取试卷详情
  if (props.paperId) {
    await getPaperDetail(props.paperId);
  }
});

/**
 * 获取大题编号（一、二、三...）
 */
const getBigQuestionNumber = (index: number): string => {
  const numbers = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
  return numbers[index] || (index + 1).toString();
};
</script>

<template>
  <div>
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <ElIcon :size="48" class="is-loading">
        <Loading />
      </ElIcon>
      <p class="loading-text">加载中...</p>
    </div>

    <!-- 错误信息 -->
    <div v-else-if="error" class="error-container">
      <ElAlert :title="error" type="error" show-icon :closable="false" />
    </div>

    <!-- 试卷内容 -->
    <div v-else class="paper-content">
      <!-- 试卷主体 -->
      <div class="paper-main">
        <!-- 右侧试卷内容 -->
        <div class="paper-body">
          <!-- 试卷标题 -->
          <div class="paper-header mb-8 text-center">
            <h1 class="paper-title mb-2 text-2xl font-bold">
              {{ paperInfo.paperName }}
            </h1>
            <div v-if="paperInfo.paperDescription" class="paper-subtitle mb-4">
              {{ paperInfo.paperDescription }}
            </div>
            <div class="paper-meta text-sm text-gray-500">
              <span class="mr-4">分类：{{ paperInfo.categoryName }}</span>
              <span class="mr-4">总题数：{{ paperInfo.questionCount }}题</span>
              <span>总分：{{ paperInfo.totalScore }}分</span>
            </div>
          </div>

          <!-- 大题列表 -->
          <div class="big-questions">
            <div
              v-for="(bigQuestion, bigIndex) in bigQuestions"
              :key="bigIndex"
              class="big-question-item mb-8"
            >
              <!-- 大题标题和分值 -->
              <div class="big-question-header mb-4">
                <h2 class="big-question-title text-lg font-bold">
                  {{ getBigQuestionNumber(bigIndex) }}、{{ bigQuestion.title }}
                  <span class="big-question-score ml-4 text-sm">
                    （共{{ bigQuestion.num }}题，{{ bigQuestion.score }}分）
                  </span>
                </h2>
              </div>

              <!-- 小题列表 -->
              <div class="small-questions pl-6">
                <div
                  v-for="(smallQuestion, smallIndex) in bigQuestion.questions"
                  :key="smallIndex"
                  class="small-question-item mb-6 last:mb-0"
                >
                  <!-- 小题内容 -->
                  <div class="small-question-content">
                    <QuestionPreview :questions="[smallQuestion]" />
                  </div>

                  <!-- 小题分值 -->
                  <!-- <div class="small-question-score mt-2 text-right">
                    <span
                      class="score-tag inline-block rounded bg-gray-100 px-2 py-0.5 text-sm text-gray-700"
                    >
                      {{ smallQuestion.score }}分
                    </span>
                  </div> -->
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.paper-preview {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 24px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 60vh;
}

.loading-text {
  margin-top: 16px;
  color: #606266;
}

.error-container {
  max-width: 800px;
  margin: 40px auto;
}

.paper-content {
  /* max-width: 1000px; */
  /* margin: 0 auto; */
}

/* 试卷主体布局 */
.paper-main {
  display: flex;
  background-color: white;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  padding: 30px;
  position: relative;
}

/* 左侧装订线和考生信息 */
.paper-side {
  width: 120px;
  margin-right: 30px;
  position: relative;
}

.binding-line {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 1px;
  background-color: #ccc;
  margin-left: 20px;
}

.student-info {
  position: absolute;
  left: 0;
  top: 30px;
  bottom: 30px;
  width: 100%;
  padding-left: 30px;
  font-size: 14px;
  line-height: 1.8;
}

.info-item {
  white-space: nowrap;
}

.seal-area {
  margin-top: 40px;
  font-size: 12px;
  color: #666;
  transform: rotate(-90deg);
  transform-origin: left top;
  margin-left: 10px;
  margin-top: 100px;
}

/* 右侧试卷内容 */
.paper-body {
  flex: 1;
  min-height: 800px;
}

/* 试卷标题 */
.paper-header {
  margin-bottom: 50px;
}

.paper-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
}

.paper-subtitle {
  font-size: 16px;
  margin-bottom: 20px;
}

.paper-meta {
  font-size: 14px;
  color: #666;
}

/* 大题样式 */
.big-question-item {
  margin-bottom: 40px;
}

.big-question-header {
  margin-bottom: 20px;
}

.big-question-title {
  font-size: 18px;
  font-weight: bold;
}

.big-question-score {
  font-size: 14px;
  color: #666;
}

/* 小题样式 */
.small-questions {
  margin-left: 20px;
}

.small-question-item {
  margin-bottom: 25px;
}

.small-question-content {
  margin-bottom: 10px;
}

.small-question-score {
  text-align: right;
  margin-top: 5px;
}

.score-tag {
  font-size: 12px;
  padding: 2px 8px;
  background-color: #f0f0f0;
  border-radius: 4px;
}

/* 页码信息 */
.page-info {
  text-align: center;
  margin-top: 60px;
  font-size: 14px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .paper-preview {
    padding: 16px;
  }

  .paper-main {
    flex-direction: column;
    padding: 20px;
  }

  .paper-side {
    width: 100%;
    margin-right: 0;
    margin-bottom: 30px;
    height: 100px;
  }

  .binding-line {
    display: none;
  }

  .student-info {
    position: relative;
    top: 0;
    padding-left: 0;
    display: flex;
    flex-wrap: wrap;
  }

  .info-item {
    width: 50%;
    margin-bottom: 10px;
  }

  .seal-area {
    display: none;
  }

  .paper-title {
    font-size: 20px;
  }

  .big-question-title {
    font-size: 16px;
  }
}
</style>
