<template>
  <div class="category-create">
    <div class="page-header">
      <h2>新增题型分类</h2>
      <el-button @click="goBack">返回列表</el-button>
    </div>

    <div class="page-content">
      <CategoryForm
          ref="formRef"
          :category-options="categoryOptions"
          @submit="handleSubmit"
          @cancel="goBack"
      />
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import CategoryForm from './CategoryForm.vue'
import { questionCategoryApi } from '@/api/question-category.js'

export default {
  name: 'QuestionCategoryCreate',
  components: {
    CategoryForm
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    const formRef = ref()
    const categoryOptions = ref([])

    const loadCategoryOptions = async () => {
      try {
        const data = await questionCategoryApi.getOptions()
        categoryOptions.value = data
      } catch (error) {
        console.error('加载分类选项失败:', error)
      }
    }

    const handleSubmit = async (formData) => {
      try {
        // 如果有parentId参数，优先使用
        if (route.query.parentId) {
          formData.parent_id = parseInt(route.query.parentId)
        }

        await questionCategoryApi.create(formData)
        ElMessage.success('创建成功')
        goBack()
      } catch (error) {
        console.error('创建分类失败:', error)
      }
    }

    const goBack = () => {
      router.push('/question-category')
    }

    onMounted(() => {
      loadCategoryOptions()
    })

    return {
      formRef,
      categoryOptions,
      handleSubmit,
      goBack
    }
  }
}
</script>

<style scoped>
.category-create {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.page-content {
  max-width: 600px;
}
</style>