<template>
  <div class="exam-create">
    <h1 class="page-title">创建考试</h1>
    
    <el-form :model="examForm" :rules="rules" ref="examFormRef" label-width="120px" class="exam-form">
      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        
        <el-form-item label="考试标题" prop="title">
          <el-input v-model="examForm.title" placeholder="请输入考试标题" />
        </el-form-item>
        
        <el-form-item label="考试描述" prop="description">
          <el-input v-model="examForm.description" type="textarea" :rows="3" placeholder="请输入考试描述" />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="考试时间" prop="timeRange">
              <el-date-picker
                v-model="examForm.timeRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="考试时长(分钟)" prop="duration">
              <el-input-number v-model="examForm.duration" :min="1" :max="300" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="总分" prop="totalScore">
              <el-input-number v-model="examForm.totalScore" :min="1" :max="1000" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="及格分数" prop="passScore">
              <el-input-number v-model="examForm.passScore" :min="1" :max="examForm.totalScore" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      
      <!-- 考试章节 -->
      <el-card class="form-card" v-for="(section, sectionIndex) in examForm.sections" :key="sectionIndex">
        <template #header>
          <div class="card-header">
            <span>章节 {{ sectionIndex + 1 }}</span>
            <el-button type="danger" link @click="removeSection(sectionIndex)">删除章节</el-button>
          </div>
        </template>
        
        <el-form-item :label="'章节标题'" :prop="`sections.${sectionIndex}.title`">
          <el-input v-model="section.title" placeholder="请输入章节标题" />
        </el-form-item>
        
        <!-- 题目列表 -->
        <div v-for="(question, questionIndex) in section.questions" :key="questionIndex" class="question-item">
          <div class="question-header">
            <h3>题目 {{ questionIndex + 1 }}</h3>
            <el-button type="danger" link @click="removeQuestion(sectionIndex, questionIndex)">删除题目</el-button>
          </div>
          
          <el-form-item :label="'题目内容'" :prop="`sections.${sectionIndex}.questions.${questionIndex}.content`">
            <el-input v-model="question.content" type="textarea" :rows="2" placeholder="请输入题目内容" />
          </el-form-item>
          
          <el-form-item :label="'题目类型'" :prop="`sections.${sectionIndex}.questions.${questionIndex}.type`">
            <el-select v-model="question.type" placeholder="选择题目类型">
              <el-option label="单选题" value="single" />
              <el-option label="多选题" value="multiple" />
              <el-option label="判断题" value="truefalse" />
              <el-option label="填空题" value="blank" />
              <el-option label="简答题" value="essay" />
            </el-select>
          </el-form-item>
          
          <el-form-item :label="'分值'" :prop="`sections.${sectionIndex}.questions.${questionIndex}.score`">
            <el-input-number v-model="question.score" :min="1" :max="100" />
          </el-form-item>
          
          <!-- 选项 (针对单选、多选、判断题) -->
          <template v-if="['single', 'multiple', 'truefalse'].includes(question.type)">
            <div v-for="(option, optionIndex) in question.options" :key="optionIndex" class="option-item">
              <el-row :gutter="10">
                <el-col :span="18">
                  <el-form-item :label="`选项 ${String.fromCharCode(65 + optionIndex)}`" :prop="`sections.${sectionIndex}.questions.${questionIndex}.options.${optionIndex}.content`">
                    <el-input v-model="option.content" placeholder="请输入选项内容" />
                  </el-form-item>
                </el-col>
                
                <el-col :span="4">
                  <el-form-item label="是否正确">
                    <el-checkbox v-model="option.isCorrect" />
                  </el-form-item>
                </el-col>
                
                <el-col :span="2" v-if="question.options.length > 2">
                  <el-button type="danger" circle icon="Delete" @click="removeOption(sectionIndex, questionIndex, optionIndex)" />
                </el-col>
              </el-row>
            </div>
            
            <el-button type="primary" plain @click="addOption(sectionIndex, questionIndex)">添加选项</el-button>
          </template>
          
          <!-- 答案 (针对填空题和简答题) -->
          <template v-if="['blank', 'essay'].includes(question.type)">
            <el-form-item :label="'参考答案'" :prop="`sections.${sectionIndex}.questions.${questionIndex}.answer`">
              <el-input v-model="question.answer" type="textarea" :rows="2" placeholder="请输入参考答案" />
            </el-form-item>
          </template>
        </div>
        
        <el-button type="primary" plain @click="addQuestion(sectionIndex)">添加题目</el-button>
      </el-card>
      
      <div class="form-actions">
        <el-button type="primary" @click="addSection">添加章节</el-button>
        <el-button type="success" @click="submitForm" :loading="submitting">保存考试</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { createExam } from '../../api/exam'
import { useRouter } from 'vue-router'

const router = useRouter()
const examFormRef = ref(null)
const submitting = ref(false)

// 考试表单数据
const examForm = reactive({
  title: '',
  description: '',
  timeRange: [],
  duration: 60,
  totalScore: 100,
  passScore: 60,
  sections: [
    {
      title: '第一章节',
      questions: [
        {
          content: '',
          type: 'single',
          score: 5,
          options: [
            { content: '', isCorrect: false },
            { content: '', isCorrect: false }
          ],
          answer: ''
        }
      ]
    }
  ]
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入考试标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入考试描述', trigger: 'blur' }
  ],
  timeRange: [
    { required: true, message: '请选择考试时间范围', trigger: 'change' }
  ],
  duration: [
    { required: true, message: '请输入考试时长', trigger: 'blur' }
  ],
  totalScore: [
    { required: true, message: '请输入总分', trigger: 'blur' }
  ],
  passScore: [
    { required: true, message: '请输入及格分数', trigger: 'blur' }
  ]
}

// 添加章节
const addSection = () => {
  examForm.sections.push({
    title: `第${examForm.sections.length + 1}章节`,
    questions: [
      {
        content: '',
        type: 'single',
        score: 5,
        options: [
          { content: '', isCorrect: false },
          { content: '', isCorrect: false }
        ],
        answer: ''
      }
    ]
  })
}

// 删除章节
const removeSection = (sectionIndex) => {
  if (examForm.sections.length <= 1) {
    ElMessage.warning('至少保留一个章节')
    return
  }
  
  ElMessageBox.confirm('确定要删除这个章节吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    examForm.sections.splice(sectionIndex, 1)
  }).catch(() => {})
}

// 添加题目
const addQuestion = (sectionIndex) => {
  examForm.sections[sectionIndex].questions.push({
    content: '',
    type: 'single',
    score: 5,
    options: [
      { content: '', isCorrect: false },
      { content: '', isCorrect: false }
    ],
    answer: ''
  })
}

// 删除题目
const removeQuestion = (sectionIndex, questionIndex) => {
  if (examForm.sections[sectionIndex].questions.length <= 1) {
    ElMessage.warning('至少保留一个题目')
    return
  }
  
  examForm.sections[sectionIndex].questions.splice(questionIndex, 1)
}

// 添加选项
const addOption = (sectionIndex, questionIndex) => {
  examForm.sections[sectionIndex].questions[questionIndex].options.push({
    content: '',
    isCorrect: false
  })
}

// 删除选项
const removeOption = (sectionIndex, questionIndex, optionIndex) => {
  if (examForm.sections[sectionIndex].questions[questionIndex].options.length <= 2) {
    ElMessage.warning('至少保留两个选项')
    return
  }
  
  examForm.sections[sectionIndex].questions[questionIndex].options.splice(optionIndex, 1)
}

// 计算总题目数
const totalQuestions = computed(() => {
  return examForm.sections.reduce((total, section) => {
    return total + section.questions.length
  }, 0)
})

// 计算总分是否匹配
const validateTotalScore = () => {
  const calculatedTotal = examForm.sections.reduce((total, section) => {
    return total + section.questions.reduce((sectionTotal, question) => {
      return sectionTotal + question.score
    }, 0)
  }, 0)
  
  return calculatedTotal === examForm.totalScore
}

// 提交表单
const submitForm = async () => {
  if (!examFormRef.value) return
  
  await examFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('请检查表单填写是否正确')
      return
    }
    
    // 验证总分
    if (!validateTotalScore()) {
      ElMessage.error(`题目总分(${calculatedTotal})与设置的总分(${examForm.totalScore})不匹配`)
      return
    }
    
    // 验证选择题是否有正确答案
    let hasError = false
    examForm.sections.forEach((section, sectionIndex) => {
      section.questions.forEach((question, questionIndex) => {
        if (['single', 'multiple'].includes(question.type)) {
          const hasCorrectOption = question.options.some(option => option.isCorrect)
          if (!hasCorrectOption) {
            ElMessage.error(`第${sectionIndex + 1}章节第${questionIndex + 1}题没有设置正确答案`)
            hasError = true
          }
          
          // 单选题只能有一个正确答案
          if (question.type === 'single' && question.options.filter(option => option.isCorrect).length > 1) {
            ElMessage.error(`第${sectionIndex + 1}章节第${questionIndex + 1}题是单选题，只能有一个正确答案`)
            hasError = true
          }
        }
      })
    })
    
    if (hasError) return
    
    // 准备提交数据
    const submitData = {
      title: examForm.title,
      description: examForm.description,
      startTime: examForm.timeRange[0],
      endTime: examForm.timeRange[1],
      duration: examForm.duration,
      totalScore: examForm.totalScore,
      passScore: examForm.passScore,
      sections: examForm.sections
    }
    
    submitting.value = true
    try {
      const res = await createExam(submitData)
      ElMessage.success('考试创建成功')
      router.push(`/admin/exams/${res.data.id}`)
    } catch (error) {
      console.error('创建考试失败:', error)
    } finally {
      submitting.value = false
    }
  })
}
</script>

<style lang="scss" scoped>
.exam-create {
  max-width: 1200px;
  margin: 0 auto;
  
  .form-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  
  .question-item {
    border: 1px solid #eee;
    border-radius: 4px;
    padding: 15px;
    margin-bottom: 15px;
    
    .question-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      
      h3 {
        margin: 0;
        font-size: 16px;
      }
    }
  }
  
  .option-item {
    margin-bottom: 10px;
  }
  
  .form-actions {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 30px;
  }
}
</style> 