<template>
  <el-dialog
    v-model="dialogVisible"
    title="新增年级"
    width="500px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <div style="margin-bottom: 16px;">
      <span style="font-weight: bold;">学校：</span>
      <span>{{ currentSchool?.schoolName }}</span>
    </div>
    
    <el-form ref="formRef" :model="form" label-width="80px">
      <el-form-item label="选择年级" prop="gradeIds">
        <el-checkbox-group v-model="form.gradeIds">
          <el-row :gutter="10">
            <el-col :span="8" v-for="item in gradeOptions" :key="item.value">
              <el-checkbox :label="item.value" style="margin-bottom: 8px;">
                {{ item.label }}
              </el-checkbox>
            </el-col>
          </el-row>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
/**
 * 新增年级弹窗
 * @author pangu
 */
import { ElMessage } from 'element-plus'
import { onMounted, ref } from 'vue'
import { addSchoolGrade, getGradeOptions } from '@/api/pangu/school'

const emit = defineEmits(['success'])

const dialogVisible = ref(false)
const submitLoading = ref(false)
const formRef = ref(null)
const currentSchool = ref(null)
const gradeOptions = ref([])

// 表单数据
const form = ref({
  schoolId: null,
  gradeIds: []
})

// 获取年级选项
const fetchGradeOptions = async () => {
  try {
    const res = await getGradeOptions()
    if (res.code === 200) {
      gradeOptions.value = res.data
    }
  } catch (error) {
    console.error('获取年级选项失败:', error)
  }
}

// 打开弹窗
const open = (school) => {
  dialogVisible.value = true
  currentSchool.value = school
  form.value = {
    schoolId: school.id,
    gradeIds: []
  }
}

// 提交表单
const handleSubmit = async () => {
  if (form.value.gradeIds.length === 0) {
    ElMessage.warning('请至少选择一个年级')
    return
  }
  
  submitLoading.value = true
  try {
    const res = await addSchoolGrade(form.value)
    if (res.code === 200) {
      ElMessage.success('添加年级成功')
      dialogVisible.value = false
      emit('success')
    }
  } catch (error) {
    console.error('添加年级失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 初始化
onMounted(() => {
  fetchGradeOptions()
})

// 暴露方法给父组件
defineExpose({ open })
</script>
