<template>
  <el-dialog
    v-model="dialogVisible"
    title="挂载年级"
    width="600px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <div style="margin-bottom: 16px;">
      <span style="font-weight: bold;">学校：</span>
      <span>{{ currentSchool?.name }}</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 gradeList" :key="item.gradeId">
              <el-checkbox :label="item.gradeId" style="margin-bottom: 8px;">
                {{ item.gradeName }}
              </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 { bindGrades, getGradeList } from '@/api/school'
import { ElMessage } from 'element-plus'
import { onMounted, ref } from 'vue'

const emit = defineEmits(['success'])

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

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

// 获取年级列表
const fetchGradeList = async () => {
  try {
    const res = await getGradeList()
    if (res.code === 200) {
      gradeList.value = res.data || []
    }
  } catch (error) {
    console.error('获取年级列表失败:', error)
  }
}

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

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

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

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