<template>
  <el-dialog
    :model-value="modelValue"
    title="分配床位"
    width="500px"
    @update:model-value="$emit('update:modelValue', $event)"
  >
    <el-form label-width="100px">
      <el-form-item label="目标床位">
        <strong>{{ data?.buildingName }} - {{ data?.roomNo }} - {{ data?.bedNo }}号床</strong>
      </el-form-item>
      <el-form-item label="选择学生">
        <el-select 
          v-model="form.studentId" 
          filterable 
          remote 
          :remote-method="remoteMethod" 
          placeholder="搜索学生姓名/学号"
          style="width: 100%"
        >
          <el-option v-for="item in studentOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="入住日期">
        <el-date-picker v-model="form.date" type="date" placeholder="选择日期" style="width: 100%" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="$emit('update:modelValue', false)">取消</el-button>
      <el-button type="primary" @click="confirmAssign">确认分配</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default: () => null
  }
})

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

const form = reactive({
  studentId: '',
  date: new Date()
})
const studentOptions = ref([])

watch(() => props.modelValue, (val) => {
  if (val) {
    form.studentId = ''
    form.date = new Date()
    studentOptions.value = []
  }
})

const remoteMethod = (query) => {
  if (query) {
    setTimeout(() => {
      studentOptions.value = [
        { value: '31901099', label: '未分配学生A (31901099)' },
        { value: '31901098', label: '未分配学生B (31901098)' },
      ]
    }, 200)
  } else {
    studentOptions.value = []
  }
}

const confirmAssign = () => {
  if (!form.studentId) return
  ElMessage.success('分配成功')
  emit('success')
  emit('update:modelValue', false)
}
</script>
