<template>
  <div>
    <!-- 所在学校 -->
    <el-form-item :label="schoolLabel" :prop="schoolProp">
      <el-select 
        v-model="formData.schoolId" 
        :placeholder="schoolPlaceholder" 
        style="width: 100%" 
        filterable 
        clearable 
        :disabled="schoolDisabled"
        @change="handleSchoolChange"
      >
        <el-option
          v-for="item in schoolOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    
    <!-- 学校班级 -->
    <el-form-item :label="schoolClassLabel" :prop="schoolClassProp" v-if="enableCampus">
      <el-select 
        v-model="formData.schoolClassIds" 
        :placeholder="schoolClassPlaceholder" 
        style="width: 100%" 
        filterable 
        clearable 
        :disabled="!formData.schoolId || schoolClassDisabled || (!!formData.campusId)"
        :multiple="multipleClass"
        @change="handleClassChange"
      >
        <el-option
          v-for="item in schoolClassOptions"
          :key="item.classId"
          :label="item.name"
          :value="item.classId"
        />
      </el-select>
    </el-form-item>
    
    <!-- 学校班级（当不启用校区时显示） -->
    <el-form-item :label="schoolClassLabel" :prop="schoolClassProp" v-if="!enableCampus">
      <el-select 
        v-model="formData.schoolClassIds" 
        :placeholder="schoolClassPlaceholder" 
        style="width: 100%" 
        filterable 
        clearable 
        :disabled="!formData.schoolId || schoolClassDisabled"
        :multiple="multipleClass"
        @change="handleClassChange"
      >
        <el-option
          v-for="item in schoolClassOptions"
          :key="item.classId"
          :label="item.name"
          :value="item.classId"
        />
      </el-select>
    </el-form-item>
    
    <!-- 培训校区 -->
    <el-form-item :label="campusLabel" :prop="campusProp" v-if="enableCampus">
      <el-select 
        v-model="formData.campusId" 
        :placeholder="campusPlaceholder" 
        style="width: 100%" 
        filterable 
        clearable 
        :disabled="campusDisabled || (!!formData.schoolId)"
        @change="handleCampusChange"
      >
        <el-option
          v-for="item in campusOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </el-form-item>

    <!-- 校区班级 -->
    <el-form-item :label="campusClassLabel" :prop="campusClassProp" v-if="enableCampus">
      <el-select 
        v-model="formData.campusClassIds" 
        :placeholder="campusClassPlaceholder" 
        style="width: 100%" 
        filterable 
        clearable 
        :disabled="!formData.campusId || campusClassDisabled || (!!formData.schoolId)"
        :multiple="multipleClass"
        @change="handleClassChange"
      >
        <el-option
          v-for="item in campusClassOptions"
          :key="item.classId"
          :label="item.name"
          :value="item.classId"
        />
      </el-select>
    </el-form-item>
  </div>
</template>

<script setup>
import { watch, onMounted, nextTick } from 'vue'
import { getClassesBySchoolId, getClassesByCampusId } from "@/api/dz/classes"
import useSchoolClassSelect from '../hooks/useSchoolClassSelect.js'

const props = defineProps({
  // 配置选项
  enableCampus: {
    type: Boolean,
    default: false
  },
  multipleClass: {
    type: Boolean,
    default: false
  },
  autoLoad: {
    type: Boolean,
    default: true
  },
  // 标签文本
  schoolLabel: {
    type: String,
    default: '所在学校'
  },
  schoolClassLabel: {
    type: String,
    default: '学校班级'
  },
  campusLabel: {
    type: String,
    default: '培训校区'
  },
  campusClassLabel: {
    type: String,
    default: '校区班级'
  },
  // 占位符
  schoolPlaceholder: {
    type: String,
    default: '请选择所在学校'
  },
  schoolClassPlaceholder: {
    type: String,
    default: '请选择学校班级'
  },
  campusPlaceholder: {
    type: String,
    default: '请选择培训校区'
  },
  campusClassPlaceholder: {
    type: String,
    default: '请选择校区班级'
  },
  // 表单属性名
  schoolProp: {
    type: String,
    default: 'schoolId'
  },
  schoolClassProp: {
    type: String,
    default: 'schoolClassIds'
  },
  campusProp: {
    type: String,
    default: 'campusId'
  },
  campusClassProp: {
    type: String,
    default: 'campusClassIds'
  },
  // 禁用状态
  schoolDisabled: {
    type: Boolean,
    default: false
  },
  schoolClassDisabled: {
    type: Boolean,
    default: false
  },
  campusDisabled: {
    type: Boolean,
    default: false
  },
  campusClassDisabled: {
    type: Boolean,
    default: false
  },
  // 外部传入的初始值
  modelValue: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

// 使用 hook
const {
  schoolOptions,
  schoolClassOptions,
  campusOptions,
  campusClassOptions,
  formData,
  loadSchoolList,
  loadCampusList,
  loadClassesBySchoolId: hookLoadClassesBySchoolId,
  loadClassesByCampusId: hookLoadClassesByCampusId,
  handleSchoolChange: hookHandleSchoolChange,
  handleCampusChange: hookHandleCampusChange
} = useSchoolClassSelect({
  enableCampus: props.enableCampus,
  multipleClass: props.multipleClass,
  autoLoad: props.autoLoad
})

// 同步外部传入的值到内部 formData
watch(() => props.modelValue, (newVal) => {
  if (newVal && typeof newVal === 'object') {
    if (newVal.schoolId !== undefined) {
      formData.value.schoolId = newVal.schoolId
      // 如果有学校ID，加载班级
      if (newVal.schoolId) {
        hookLoadClassesBySchoolId(newVal.schoolId)
      }
    }
    if (newVal.schoolClassIds !== undefined) {
      formData.value.schoolClassIds = newVal.schoolClassIds
    }
    if (newVal.campusId !== undefined) {
      formData.value.campusId = newVal.campusId
      // 如果有校区ID，加载班级
      if (newVal.campusId && props.enableCampus) {
        hookLoadClassesByCampusId(newVal.campusId)
      }
    }
    if (newVal.campusClassIds !== undefined) {
      formData.value.campusClassIds = newVal.campusClassIds
    }
  }
}, { immediate: true, deep: true })

// 监听内部 formData 变化，同步到外部
watch(() => formData.value, (newVal) => {
  const updateData = {
    schoolId: newVal.schoolId,
    schoolClassIds: newVal.schoolClassIds,
    campusId: newVal.campusId,
    campusClassIds: newVal.campusClassIds
  }
  emit('update:modelValue', updateData)
  emit('change', updateData)
}, { deep: true })

// 学校变化处理
async function handleSchoolChange(schoolId) {
  await hookHandleSchoolChange(schoolId)
  emit('change', { ...formData.value })
}

// 校区变化处理
async function handleCampusChange(campusId) {
  await hookHandleCampusChange(campusId)
  emit('change', { ...formData.value })
}

// 班级变化处理
function handleClassChange() {
  emit('change', { ...formData.value })
}

// 加载学校班级的方法（包装 hook 的方法）
const loadClassesBySchoolId = (schoolId) => {
  return hookLoadClassesBySchoolId(schoolId)
}

// 加载校区班级的方法（包装 hook 的方法）
const loadClassesByCampusId = (campusId) => {
  return hookLoadClassesByCampusId(campusId)
}

// 重置方法
const reset = () => {
  formData.value = {
    schoolId: null,
    schoolClassIds: props.multipleClass ? [] : null,
    campusId: null,
    campusClassIds: props.multipleClass ? [] : null
  }
  schoolClassOptions.value = []
  campusClassOptions.value = []
}

// 暴露方法供外部调用
defineExpose({
  formData,
  loadSchoolList,
  loadCampusList,
  loadClassesBySchoolId,
  loadClassesByCampusId,
  reset
})

</script>

