<script setup lang="ts">
import { ref, computed } from 'vue';
import { ElAnchor, ElAnchorLink, ElCollapse, ElCollapseItem, ElTable } from 'element-plus';
import ExamPreview from './examPreview.vue';

// 试卷表单数据
const examForm = ref({
  examName: '',
  examCategory: '',
});

// 试卷题目数据
const examQuestions = ref([
  {
    title: '第一题 选择题',
    fixedQuestions: [
      { type: '填空题', count: 120, score: 0 },
      { type: '简答题', count: 120, score: 0 },
      { type: '单选题', count: 120, score: 0 },
      { type: '多选题', count: 120, score: 0 },
    ],
    randomQuestions: [
      { type: '填空题', count: 120, score: 0 },
      { type: '简答题', count: 120, score: 0 },
      { type: '单选题', count: 120, score: 0 },
      { type: '多选题', count: 120, score: 0 },
    ],
  },
  {
    title: '第二题 填空题',
    fixedQuestions: [],
    randomQuestions: [],
  },
  {
    title: '第三题 判断题',
    fixedQuestions: [],
    randomQuestions: [],
  },
]);

// 折叠面板状态，默认展开所有面板
const activeCollapse = ref<(string | number | boolean)[]>(examQuestions.value.map((_, index) => index));

// 计算总题数
const totalQuestions = computed(() => examQuestions.value.length);

// 计算小题总数
const totalSubQuestions = computed(() => {
  return examQuestions.value.reduce((total, question) => {
    return (
      total + question.fixedQuestions.length + question.randomQuestions.length
    );
  }, 0);
});

// 计算总分
const totalScore = computed(() => {
  let score = 0;
  examQuestions.value.forEach((question) => {
    question.fixedQuestions.forEach((item) => {
      score += item.score;
    });
    question.randomQuestions.forEach((item) => {
      score += item.score;
    });
  });
  return score;
});

// 获取单个题目总分
const getQuestionTotalScore = (index: number) => {
  const question = examQuestions.value[index];
  let score = 0;
  question.fixedQuestions.forEach((item) => {
    score += item.score;
  });
  question.randomQuestions.forEach((item) => {
    score += item.score;
  });
  return score;
};

// 添加大题
const addBigQuestion = () => {
  examQuestions.value.push({
    title: `第${examQuestions.value.length + 1}题 新题目`,
    fixedQuestions: [],
    randomQuestions: [],
  });
};
// 容器引用
const containerRef = ref<HTMLElement | null>(null);
// 试题表格引用
const questionTable = ref<InstanceType<typeof ElTable> | null>(null);

const handleClick = (e: MouseEvent) => {
  e.preventDefault();
};

// 弹框相关
const dialogVisible = ref(false);
const currentQuestionIndex = ref(-1);
const currentQuestionType = ref(''); // 'fixed' or 'random'

// 搜索表单
const searchForm = ref({
  questionName: '',
  questionType: '',
  questionCategory: '',
  questionDifficulty: '',
});

// 模拟试题数据
const questionList = ref([
  { id: 1, name: '题目1', type: '单选题', category: '分类1', difficulty: '简单' },
  { id: 2, name: '题目2', type: '多选题', category: '分类2', difficulty: '中等' },
  { id: 3, name: '题目3', type: '填空题', category: '分类1', difficulty: '困难' },
  { id: 4, name: '题目4', type: '简答题', category: '分类3', difficulty: '简单' },
  { id: 5, name: '题目5', type: '判断题', category: '分类2', difficulty: '中等' },
]);

// 分页数据
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(37);

// 存储选中的试题
const selectedQuestions = ref<any[]>([]);

// 处理选择变化
const handleSelectionChange = (val: any[]) => {
  selectedQuestions.value = val;
};

// 打开弹框
const openDialog = (index: number, type: string) => {
  currentQuestionIndex.value = index;
  currentQuestionType.value = type;
  // 清空之前的选择
  selectedQuestions.value = [];
  dialogVisible.value = true;
};

// 关闭弹框
const closeDialog = () => {
  dialogVisible.value = false;
};

// 查询
const handleSearch = () => {
  // 实际项目中这里会调用API获取数据
  console.log('搜索参数:', searchForm.value);
};

// 重置
const handleReset = () => {
  searchForm.value = {
    questionName: '',
    questionType: '',
    questionCategory: '',
    questionDifficulty: '',
  };
};

// 预览
const previewQuestion = (id: number) => {
  console.log('预览题目:', id);
};

// 分页方法
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  // 实际项目中这里会重新调用API获取数据
  console.log('每页条数:', size);
};

const handleCurrentChange = (current: number) => {
  currentPage.value = current;
  // 实际项目中这里会重新调用API获取数据
  console.log('当前页码:', current);
};

// 保存选中的试题
const saveQuestions = () => {
  if (currentQuestionIndex.value === -1 || !currentQuestionType.value) {
    return;
  }

  // 使用通过handleSelectionChange方法存储的选中数据
  const selectedRows = selectedQuestions.value;
  
  if (selectedRows.length === 0) {
    return;
  }

  // 根据类型添加到对应的试题列表
  const question = examQuestions.value[currentQuestionIndex.value];
  if (currentQuestionType.value === 'fixed') {
    // 为每个选中的试题创建一个新的对象，包含必要的字段
    selectedRows.forEach((row: any) => {
      question.fixedQuestions.push({
        type: row.type,
        count: 1, // 每个试题算1个
        score: 0 // 默认分数为0
      });
    });
  } else if (currentQuestionType.value === 'random') {
    // 为每个选中的试题创建一个新的对象，包含必要的字段
    selectedRows.forEach((row: any) => {
      question.randomQuestions.push({
        type: row.type,
        count: 1, // 每个试题算1个
        score: 0 // 默认分数为0
      });
    });
  }

  // 关闭弹框
  closeDialog();
};

// 随机试题设置表单
const randomQuestionForm = ref({
  questionTypes: [] as string[],
  questionCategories: [] as string[],
  questionDifficulty: '',
  questionCount: 1,
});

// 题型选项
const questionTypeOptions = [
  { label: '单选题', value: '单选题' },
  { label: '多选题', value: '多选题' },
  { label: '填空题', value: '填空题' },
  { label: '简答题', value: '简答题' },
  { label: '判断题', value: '判断题' },
];

// 分类选项
const questionCategoryOptions = [
  { label: '分类1', value: '分类1' },
  { label: '分类2', value: '分类2' },
  { label: '分类3', value: '分类3' },
];

// 难度选项
const questionDifficultyOptions = [
  { label: '简单', value: '简单' },
  { label: '中等', value: '中等' },
  { label: '困难', value: '困难' },
];

// 预览相关
const previewDialogVisible = ref(false);
const previewQuestions = ref<any[]>([]);

// 打开预览弹框
const openPreviewDialog = (index: number, questionType: string, questionIndex: number) => {
  const question = examQuestions.value[index];
  const targetQuestions = questionType === 'fixed' ? question.fixedQuestions : question.randomQuestions;
  const selectedQuestion = targetQuestions[questionIndex];
  
  // 模拟生成预览数据
  generatePreviewData(selectedQuestion.type, selectedQuestion.count);
  
  previewDialogVisible.value = true;
};

// 关闭预览弹框
const closePreviewDialog = () => {
  previewDialogVisible.value = false;
};

// 生成预览数据
const generatePreviewData = (type: string, count: number) => {
  previewQuestions.value = [];
  
  for (let i = 0; i < count; i++) {
    switch (type) {
      case '单选题':
        previewQuestions.value.push({
          id: `single-${i}`,
          questionType: '单选题',
          questionTitle: '这是本题的题目，请选择',
          options: [
            { content: '答案1', isCorrect: true },
            { content: '答案2', isCorrect: false },
            { content: '答案3', isCorrect: false },
            { content: '答案4', isCorrect: false }
          ],
          score: 2
        });
        break;
      case '多选题':
        previewQuestions.value.push({
          id: `multiple-${i}`,
          questionType: '多选题',
          questionTitle: '这是本题的题目，请选择',
          options: [
            { content: '答案1', isCorrect: true },
            { content: '答案2', isCorrect: true },
            { content: '答案3', isCorrect: false },
            { content: '答案4', isCorrect: false }
          ],
          score: 4
        });
        break;
      case '判断题':
        previewQuestions.value.push({
          id: `judge-${i}`,
          questionType: '判断题',
          questionTitle: '这是本题的题目，请判断',
          options: [
            { content: '正确', isCorrect: true },
            { content: '错误', isCorrect: false }
          ],
          score: 1
        });
        break;
      case '填空题':
        previewQuestions.value.push({
          id: `fill-${i}`,
          questionType: '填空题',
          questionTitle: '这是本题的题目，请作答',
          correctAnswer: '这是正确答案这是正确答案这是正确答案这是正确答案这是正确答案这是正确答案。这是正确答案这是正确答案这是正确答案这是正确答案这是正确答案这是正确答案这是正确答案',
          score: 3
        });
        break;
      case '简答题':
        previewQuestions.value.push({
          id: `essay-${i}`,
          questionType: '简答题',
          questionTitle: '这是本题的题目，请作答',
          correctAnswer: '这是正确答案这是正确答案这是正确答案这是正确答案这是正确答案这是正确答案。这是正确答案这是正确答案这是正确答案这是正确答案这是正确答案这是正确答案这是正确答案',
          score: 6
        });
        break;
    }
  }
};

// 保存随机试题设置
const saveRandomQuestions = () => {
  if (currentQuestionIndex.value === -1) {
    return;
  }

  // 获取当前设置的随机试题参数
  const { questionTypes, questionCategories, questionDifficulty, questionCount } = randomQuestionForm.value;

  // 确保至少选择了一种题型
  if (!questionTypes || questionTypes.length === 0) {
    return;
  }

  // 根据类型添加到对应的试题列表
  const question = examQuestions.value[currentQuestionIndex.value];
  
  // 为每种选中的题型创建一个随机试题设置
  questionTypes.forEach((type: string) => {
    question.randomQuestions.push({
      type: type,
      count: questionCount,
      score: 0 // 默认分数为0
    });
  });

  // 关闭弹框
  closeDialog();
};
</script>

<template>
  <div class="exam-edit-container">
    <!-- 顶部区域 -->
    <div class="top-section">
      <div class="left-section">
        <div class="form-item">
          <label class="label">试卷名称：</label>
          <el-input
            v-model="examForm.examName"
            placeholder="请输入试卷名称"
            :maxlength="30"
            show-word-limit
            class="input"
          />
        </div>
        <div class="form-item">
          <label class="label">试卷分类：</label>
          <el-select
            v-model="examForm.examCategory"
            placeholder="请选择"
            class="select"
          >
            <el-option label="选择题" value="1" />
            <el-option label="填空题" value="2" />
            <el-option label="简答题" value="3" />
            <el-option label="判断题" value="4" />
          </el-select>
        </div>
      </div>
      <div class="right-section">
        <div class="stats">
          <span>{{ totalQuestions }}大题</span>
          <span class="separator">|</span>
          <span>{{ totalSubQuestions }}小题</span>
          <span class="separator">|</span>
          <span>总分：{{ totalScore }}</span>
        </div>
        <el-button type="primary" size="default" class="save-btn">
          保存
        </el-button>
      </div>
    </div>

    <!-- 主体区域 -->
    <div class="main-section">
      <!-- 左侧导航 -->
      <div class="left-nav">
        <div class="nav-title">大题导航</div>
        <ElAnchor  
            :container="containerRef"
            direction="vertical"
            default-active="question-0"
            type="default"
            :offset="30"
            @click="handleClick">
            <ElAnchorLink
              v-for="(question, index) in examQuestions"
              :key="index"
              :href="`#question-${index}`"
              :title="question.title"
            />
        </ElAnchor>
      </div>
      <!-- 右侧内容 -->
      <div class="right-content" ref="containerRef">
        <div
          v-for="(question, index) in examQuestions"
          :key="index"
          :id="`question-${index}`"
          class="question-block"
        >
          <!-- 移除原来的question-header -->
          <el-collapse v-model="activeCollapse">
            <el-collapse-item :name="index">
              <template #title>
                <div style="display: flex; justify-content: space-between; align-items: center; font-size: 18px; width: 100%;">
                  <span>{{question.title}}</span>
                  <span>合计：{{getQuestionTotalScore(index)}}分</span>
                </div>
              </template>
              <!-- 固定试题区块 -->
              <div class="question-type-section">
                <div class="section-title">固定试题</div>
                <el-table :data="question.fixedQuestions" style="width: 100%" :header-cell-style="{ backgroundColor: '#F7F9FA', color: '#31373D' }">
                  <el-table-column prop="type" label="试题类型" />
                  <el-table-column prop="count" label="试题数" />
                  <el-table-column prop="score" label="每道题分数" >
                    <template #default="scope">
                      <el-input-number
                        v-model="scope.row.score"
                        :min="0"
                        :max="100"
                        size="small"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" >
                    <template #default="scope">
                      <el-button type="text" size="small" class="preview-btn" @click="openPreviewDialog(index, 'fixed', scope.$index)">
                        预览
                      </el-button>
                      <el-button type="text" size="small" class="delete-btn">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-button type="text" icon="Plus" class="add-question-btn" @click="openDialog(index, 'fixed')">
                  + 试题库中选题
                </el-button>
              </div>
              
              <!-- 随机试题区块 -->
              <div class="question-type-section">
                <div class="section-title">随机试题</div>
                <el-table :data="question.randomQuestions" style="width: 100%" :header-cell-style="{ backgroundColor: '#F7F9FA', color: '#31373D' }">
                  <el-table-column prop="type" label="试题类型" />
                  <el-table-column prop="count" label="试题数" />
                  <el-table-column prop="score" label="每道题分数" >
                    <template #default="scope">
                      <el-input-number
                        v-model="scope.row.score"
                        :min="0"
                        :max="100"
                        size="small"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" >
                    <template #default="scope">
                      <el-button type="text" size="small" class="preview-btn" @click="openPreviewDialog(index, 'random', scope.$index)">
                        预览
                      </el-button>
                      <el-button type="text" size="small" class="delete-btn">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-button type="text" icon="Plus" class="add-question-btn" @click="openDialog(index, 'random')">
                  + 试题库中选题
                </el-button>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>

        <el-button
          type="dashed"
          icon="Plus"
          class="add-big-question-btn"
          @click="addBigQuestion"
        >
          + 添加大题
        </el-button>
      </div>
    </div>
  </div>

  <!-- 添加固定试题弹框 -->
  <el-dialog
    v-if="currentQuestionType === 'fixed'"
    title="添加固定试题"
    v-model="dialogVisible"
    width="1000px"
  >
    <!-- 搜索表单 -->
    <div class="search-form" style="margin-bottom: 20px;">
      <el-form :model="searchForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="题目名称">
              <el-input v-model="searchForm.questionName" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="试题题型">
              <el-select v-model="searchForm.questionType" placeholder="请选择">
                <el-option label="单选题" value="单选题" />
                <el-option label="多选题" value="多选题" />
                <el-option label="填空题" value="填空题" />
                <el-option label="简答题" value="简答题" />
                <el-option label="判断题" value="判断题" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="试题分类">
              <el-select v-model="searchForm.questionCategory" placeholder="请选择">
                <el-option label="分类1" value="分类1" />
                <el-option label="分类2" value="分类2" />
                <el-option label="分类3" value="分类3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="试题难度">
              <el-select v-model="searchForm.questionDifficulty" placeholder="请选择">
                <el-option label="简单" value="简单" />
                <el-option label="中等" value="中等" />
                <el-option label="困难" value="困难" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: right;">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 试题列表 -->
    <el-table ref="questionTable" :data="questionList" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="题目名称" />
      <el-table-column prop="type" label="试题题型" />
      <el-table-column prop="category" label="试题分类" />
      <el-table-column prop="difficulty" label="试题难度" />
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button type="text" size="small" @click="previewQuestion(scope.row.id)">预览</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination" style="margin-top: 20px; text-align: right;">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveQuestions">保存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 添加随机试题弹框 -->
  <el-dialog
    v-if="currentQuestionType === 'random'"
    title="添加随机试题"
    v-model="dialogVisible"
    width="500px"
  >
    <el-form :model="randomQuestionForm" label-width="100px">
      <el-form-item label="试题类型">
        <el-select
          v-model="randomQuestionForm.questionTypes"
          multiple
          placeholder="请选择试题类型"
          style="width: 100%"
        >
          <el-option
            v-for="option in questionTypeOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="试题分类">
        <el-select
          v-model="randomQuestionForm.questionCategories"
          multiple
          placeholder="请选择试题分类"
          style="width: 100%"
        >
          <el-option
            v-for="option in questionCategoryOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="试题难度">
        <el-select
          v-model="randomQuestionForm.questionDifficulty"
          placeholder="请选择试题难度"
          style="width: 100%"
        >
          <el-option
            v-for="option in questionDifficultyOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="试题数量">
        <el-input-number
          v-model="randomQuestionForm.questionCount"
          :min="1"
          :max="100"
          placeholder="请输入试题数量"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>

    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveRandomQuestions">保存</el-button>
      </span>
    </template>
  </el-dialog>

<!-- 预览弹框 -->
<el-dialog
  title="试题预览"
  v-model="previewDialogVisible"
  width="800px"
>
  <ExamPreview :questions="previewQuestions" />
</el-dialog>
</template>

<style scoped>
  
  .exam-edit-container {
    padding: 1rem;
    background-color: #f5f7fa;
    height: calc(100vh - 90px);
  }

  /* 顶部区域 */
  .top-section {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 10px;
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .left-section {
    display: flex;
    flex-direction: column;
    gap: 20px;
    flex: 1;
  }

  .form-item {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .label {
    font-size: 14px;
    color: #000;
    min-width: 80px;
    font-weight: 400;
    text-align: right;
  }

  .input {
    width: 400px;
  }

  .select {
    width: 230px;
  }

  .right-section {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 15px;
  }

  .stats {
    display: flex;
    align-items: center;
    gap: 15px;
    font-size: 14px;
    color: #303133;
  }

  .separator {
    color: #dcdfe6;
    font-size: 16px;
  }

  .save-btn {
    width: 100px;
    margin-top: 18px;
  }

  /* 主体区域 */
  .main-section {
    display: flex;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  /* 左侧导航 */
  .left-nav {
    width: 350px;
    padding: 20px;
    margin-right: 10px;
    background-color: white;
    height: calc(100vh - 245px);
  }

  .nav-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
    color: #303133;
  }

  /* ElAnchor and ElAnchorLink styles */
  :deep(.el-anchor) {
    padding-left: 0;
  }
  :deep(.el-anchor__list) {
    padding-left: 0 !important;
  }

  :deep(.el-anchor__link) { 
    padding-left: 15px;
    margin-bottom: 10px;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
    background-color: #ffffff;
    border: 1px solid #e6e8eb;
    position: relative;
    width: 315px;
    height: 34px;
    color: #303133;
    box-sizing: border-box;
  }

  :deep(.el-anchor__link:hover) {
    background-color: #ecf5ff;
    color: #409eff;
  }

  :deep(.el-anchor__link.is-active) {
    background-color: #ecf5ff;
    color: #409eff;
    border-left: 3px solid #409eff;
  }
  :deep(.el-anchor__link-title) {
    font-size: 14px;
    font-weight: 400;
    color: #303133;
    padding: 0;
    white-space: normal;
    line-height: 1.4;
  }

  :deep(.el-anchor__link.active .el-anchor__link-title) { 
    color: #409eff;
  }

  :deep(.el-anchor-fix) {
    display: none;
  }

  /* 右侧内容 */
  .right-content {
    flex: 1;
    background-color: white;
    border-radius: 8px;
    height: calc(100vh - 245px);
    overflow-y: auto;
    /* 隐藏滚动条 */
    -ms-overflow-style: none;  /* Internet Explorer 10+ */
    scrollbar-width: none;  /* Firefox */
    ::-webkit-scrollbar {
      display: none;
    }
  }

  /* 题目块 */
  .question-block {
    margin-bottom: 20px;
    padding: 0px 20px;
    background-color: #ffffff;
    border-radius: 8px;
  }

  /* 题目类型区块 */
  .question-type-section {
    margin-bottom: 20px;
    padding: 15px;
    background-color: white;
    border-radius: 6px;
  }

  .section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
    color: #303133;
  }

  .add-question-btn {
    color: #409eff;
    margin-top: 10px;
  }

  /* 添加大题按钮 */
  .add-big-question-btn {
    width: 100%;
    margin-top: 20px;
  }

  /* 操作按钮样式 */
  .preview-btn {
    color: #409eff;
    margin-right: 10px;
  }

  .delete-btn {
    color: #f56c6c;
  }

  /* 响应式设计 */
  @media (max-width: 1200px) {
    .input,
    .select {
      width: 250px;
    }
  }

  @media (max-width: 768px) {
    .top-section {
      flex-direction: column;
    }

    .right-section {
      align-items: flex-start;
    }

    .main-section {
      flex-direction: column;
    }

    .left-nav {
      width: 100%;
      border-right: none;
      border-bottom: 1px solid #e6e8eb;
      padding-right: 0;
      padding-bottom: 20px;
      margin-bottom: 20px;
    }

    .right-content {
      padding-left: 0;
    }
  }
</style>
