<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>{{ currentGrade?.name }}</span>
    </div>
    
    <el-form ref="formRef" :model="form" label-width="80px">
      <el-form-item label="选择班级" prop="classIds">
        <el-checkbox-group v-model="form.classIds">
          <el-row :gutter="10">
            <el-col :span="8" v-for="item in classList" :key="item.classId">
              <el-checkbox :label="item.classId" style="margin-bottom: 8px;">
                {{ item.className }}
              </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 { bindClasses, getClassList } 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 currentGrade = ref(null)
const classList = ref([])

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

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

// 打开弹窗
const open = (grade) => {
  dialogVisible.value = true
  currentGrade.value = grade
  form.value = {
    schoolGradeId: grade.schoolGradeId,
    classIds: []
  }
}

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

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

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