import { reactive, ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { getUserCourseCategories } from '@/api/user'

/**
 * 课程基本信息管理
 */
export function useCourseForm() {
  // 课程基本信息
  const courseForm = reactive({
    title: '',
    description: '',
    cateId: '',
    isFree: true,
    courseLevel: 2
  })
  
  // 分类数据
  const courseCategories = ref([])
  
  // 加载分类数据
  const loadCategories = async () => {
    try {
      const response = await getUserCourseCategories()
      if (response && response.code === 200) {
        // 过滤出课程分类 (type === 1)
        courseCategories.value = response.data.filter(category => category.type === 1)
      }
    } catch (error) {
      console.error('获取课程分类失败:', error)
      courseCategories.value = []
    }
  }
  
  // 计算属性
  const levelText = computed(() => {
    switch (courseForm.courseLevel) {
      case 1: return '初级'
      case 2: return '中级'
      case 3: return '高级'
      default: return '未设置'
    }
  })
  
  const canGoNextFromStep1 = computed(() => {
    return !!courseForm.title.trim() && 
           !!courseForm.cateId && 
           (courseForm.isFree === true || courseForm.isFree === false) &&
           !!courseForm.description?.trim()
  })
  
  // 验证第一步
  const validateStep1 = (courseCoverFile = null) => {
    if (!courseForm.title.trim()) {
      ElMessage.error('请填写课程标题')
      return false
    }
    
    if (!courseForm.cateId) {
      ElMessage.error('请选择课程分类')
      return false
    }
    
    if (courseForm.isFree === null || courseForm.isFree === undefined) {
      ElMessage.error('请选择是否免费')
      return false
    }
    
    if (!courseCoverFile) {
      ElMessage.error('请上传课程封面')
      return false
    }
    
    if (!courseForm.description || !courseForm.description.trim()) {
      ElMessage.error('请填写课程描述')
      return false
    }
    
    return true
  }
  
  // 重置表单
  const resetForm = () => {
    courseForm.title = ''
    courseForm.description = ''
    courseForm.cateId = ''
    courseForm.isFree = true
    courseForm.courseLevel = 2
  }
  
  return {
    courseForm,
    courseCategories,
    levelText,
    canGoNextFromStep1,
    loadCategories,
    validateStep1,
    resetForm
  }
}
