<template>
  <el-dialog 
    title="新增住宿生" 
    v-model="visible"
    :close-on-click-modal="false" 
    draggable
    width="800px">
    <el-form 
      ref="dataFormRef" 
      :model="form" 
      :rules="dataRules" 
      label-width="100px" 
      :validate-on-rule-change="false"
      v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item label="班级" prop="classCode">
            <el-select 
              v-model="form.classCode" 
              placeholder="请选择班级" 
              clearable
              filterable
              style="width: 100%"
              @change="handleClassChange">
              <el-option
                v-for="item in classList"
                :key="item.classCode"
                :label="item.classNo"
                :value="item.classCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="姓名" prop="realName">
            <el-select 
              v-model="form.stuNo" 
              placeholder="请选择姓名" 
              clearable
              filterable
              style="width: 100%"
              :disabled="!form.classCode"
              @change="handleStudentChange">
              <el-option
                v-for="item in studentList"
                :key="item.stuNo"
                :label="item.realName"
                :value="item.stuNo">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="学号" prop="stuNo">
            <el-input 
              v-model="form.stuNo" 
              placeholder="学号" 
              disabled />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="房间号" prop="roomNo">
            <el-select 
              v-model="form.roomNo" 
              placeholder="请选择房间号" 
              clearable
              filterable
              style="width: 100%"
              @change="handleRoomChange">
              <el-option
                v-for="item in roomList"
                :key="item.roomNo"
                :label="item.roomNo"
                :value="item.roomNo">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="床位号" prop="bedNo">
            <el-select 
              v-model="form.bedNo" 
              placeholder="请选择床位号" 
              clearable
              style="width: 100%">
              <el-option
                v-for="item in bedNoList"
                :key="item.bedNo"
                :value="item.bedNo">
                <span :class="{ 'bed-option-occupied': item.haveStudent }">
                  {{ item.bedNo }}{{ item.haveStudent ? ' (有人)' : '' }}
                </span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="是否为宿舍长" prop="isLeader">
            <el-select 
              v-model="form.isLeader" 
              placeholder="请选择" 
              clearable
              style="width: 100%">
              <el-option label="是" value="1" />
              <el-option label="否" value="0" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确 认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="DormRoomStudentFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj } from '/@/api/stuwork/dormroomstudent'
import { getRoomList } from '/@/api/stuwork/dormroom'
import { fearchRoomStuNum } from '/@/api/stuwork/dormroomstudent'
import { getClassListByRole } from '/@/api/basic/basicclass'
import { fetchList as getStudentList } from '/@/api/basic/basicstudentinfo'

const emit = defineEmits(['refresh'])

// 定义变量内容
const dataFormRef = ref()
const visible = ref(false)
const loading = ref(false)
const classList = ref<any[]>([])
const studentList = ref<any[]>([])
const roomList = ref<any[]>([])
// 床位列表：支持 haveStudent 标记（true=有人，false=无人）
const bedNoList = ref<Array<{ bedNo: string; haveStudent: boolean }>>([])

// 提交表单数据
const form = reactive({
  classCode: '',
  realName: '',
  stuNo: '',
  roomNo: '',
  bedNo: '',
  isLeader: '0'
})

// 定义校验规则
const dataRules = {
  classCode: [
    { required: true, message: '请选择班级', trigger: 'change' }
  ],
  stuNo: [
    { required: true, message: '请选择姓名', trigger: 'change' }
  ],
  roomNo: [
    { required: true, message: '请选择房间号', trigger: 'change' }
  ],
  bedNo: [
    { required: true, message: '请选择床位号', trigger: 'change' }
  ],
  isLeader: [
    { required: true, message: '请选择是否为宿舍长', trigger: 'change' }
  ]
}

// 班级变化时获取学生列表
const handleClassChange = async (classCode: string) => {
  if (!classCode) {
    studentList.value = []
    form.stuNo = ''
    form.realName = ''
    return
  }
  
  try {
    const res = await getStudentList({
      classCode: classCode,
      current: 1,
      size: 1000
    })
    if (res.data && res.data.records) {
      studentList.value = res.data.records
    } else {
      studentList.value = []
    }
    form.stuNo = ''
    form.realName = ''
  } catch (err) {
    studentList.value = []
    form.stuNo = ''
    form.realName = ''
  }
}

// 学生选择变化
const handleStudentChange = (stuNo: string) => {
  const student = studentList.value.find(item => item.stuNo === stuNo)
  if (student) {
    form.realName = student.realName || ''
  }
}

// 房间号变化时获取床位号列表（支持 haveStudent：true=有人，false=无人）
const handleRoomChange = async (roomNo: string) => {
  if (!roomNo) {
    bedNoList.value = []
    form.bedNo = ''
    return
  }

  const toBedItem = (item: any): { bedNo: string; haveStudent: boolean } => {
    if (typeof item === 'number' || typeof item === 'string') {
      return { bedNo: String(item), haveStudent: false }
    }
    return {
      bedNo: String(item?.bedNo ?? item?.value ?? item ?? ''),
      haveStudent: !!(item && item.haveStudent === true)
    }
  }

  try {
    const res = await fearchRoomStuNum(roomNo)
    if (res.data) {
      if (Array.isArray(res.data)) {
        bedNoList.value = res.data.map(toBedItem).filter((b) => b.bedNo)
      } else if (res.data.bedNos && Array.isArray(res.data.bedNos)) {
        bedNoList.value = res.data.bedNos.map((item: any) =>
          toBedItem(typeof item === 'object' ? item : { bedNo: String(item), haveStudent: false })
        )
      } else {
        bedNoList.value = []
      }
    } else {
      bedNoList.value = []
    }
    form.bedNo = ''
  } catch (err) {
    bedNoList.value = []
    form.bedNo = ''
  }
}

// 打开弹窗
const openDialog = async () => {
  visible.value = true
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.classCode = ''
    form.realName = ''
    form.stuNo = ''
    form.roomNo = ''
    form.bedNo = ''
    form.isLeader = '0'
    studentList.value = []
    bedNoList.value = []
  })
}

// 提交表单
const onSubmit = async () => {
  if (!dataFormRef.value) return
  
  await dataFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    loading.value = true
    try {
      await addObj({
        roomNo: form.roomNo,
        bedNo: form.bedNo,
        stuNo: form.stuNo,
        isLeader: form.isLeader
      })
      useMessage().success('新增成功')
      visible.value = false
      emit('refresh')
    } catch (err: any) {
      useMessage().error(err.msg || '新增失败')
    } finally {
      loading.value = false
    }
  })
}

// 获取班级列表
const getClassListData = async () => {
  try {
    const res = await getClassListByRole()
    if (res.data) {
      classList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    classList.value = []
  }
}

// 获取房间号列表
const getRoomListData = async () => {
  try {
    const res = await getRoomList()
    if (res.data) {
      roomList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    roomList.value = []
  }
}

// 初始化
onMounted(() => {
  getClassListData()
  getRoomListData()
})

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

<style scoped lang="scss">
.bed-option-occupied {
  color: var(--el-color-warning);
}
</style>
