<template>
  <el-dialog v-model="visible" title="访客登记" width="500px">
    <el-form ref="formRef" :model="form" label-width="80px">
      <el-form-item label="访客姓名">
        <el-input v-model="form.visitorName" />
      </el-form-item>
      <el-form-item label="联系电话">
        <el-input v-model="form.phone" />
      </el-form-item>
      <el-form-item label="身份证号">
        <el-input v-model="form.idCard" />
      </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-input v-model="form.reason" type="textarea" />
      </el-form-item>
      <el-form-item label="预约时间">
        <el-date-picker v-model="form.visitTime" type="datetime" placeholder="选择时间" style="width: 100%" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">提交登记</el-button>
    </template>
  </el-dialog>
</template>

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

const emit = defineEmits(['success'])

const visible = ref(false)
const studentOptions = ref([])

const form = reactive({
  visitorName: '',
  phone: '',
  idCard: '',
  studentId: '',
  reason: '',
  visitTime: ''
})

const open = () => {
  Object.assign(form, { visitorName: '', phone: '', idCard: '', studentId: '', reason: '', visitTime: '' })
  visible.value = true
}

const remoteMethod = (query) => {
  if (query) {
    setTimeout(() => {
      studentOptions.value = [
        { value: '31901001', label: '梁健 (31901001)' },
        { value: '31901002', label: '鲁永波 (31901002)' },
      ]
    }, 200)
  } else {
    studentOptions.value = []
  }
}

const handleSubmit = () => {
  visible.value = false
  ElMessage.success('登记成功，访客凭证已生成')
  emit('success')
}

defineExpose({
  open
})
</script>
