<template>
  <div>
    <el-dialog v-model="newStuCheckInDialog" width="600" title="新生报到">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px"
               class="demo-ruleForm">
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="form.name"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio v-for="item in genderData" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="form.idNumber"></el-input>
        </el-form-item>

        <el-form-item label="报到状态" prop="checkInStatus">
          <el-select v-model="form.checkInStatus" filterable placeholder="请选择报到状态">
            <el-option
              v-for="item in checkInStatusData"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否住宿" prop="isRoom" v-if="isRoomTab">
          <el-select v-model="form.isRoom" filterable placeholder="是否住宿">
            <el-option
              v-for="item in yesOrNoData"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="宿舍号" prop="roomNo" v-if="isRoomTab && form.isRoom=='1'">
          <el-select
            v-model="form.roomNo"
            filterable
            remote
            placeholder="请选择宿舍号"
            :remote-method="remoteMethod"
            @change="handleRoomNoChange"
            :loading="loading"
          >
            <el-option
              v-for="item in roomNoList"
              :key="item.id"
              :label="item.roomNo"
              :value="item.roomNo">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="床号" prop="bedNo" v-if="isRoomTab && form.isRoom=='1'">
          <el-select v-model="form.bedNo" filterable placeholder="请选择床号" :key="bedNoKey">
            <el-option
              v-for="item in bedNoData"
              :key="item.bedNo"
              :label="item.bedNo"
              :value="item.bedNo"
              :disabled="isRoomDisable(item.notBedNo)">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" :rows="2"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="newStuCheckInDialog = false">取消</el-button>
        <el-button type="primary" @click="checkIn" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { useMessage } from '/@/hooks/message'
import { fearchRoomStuNum } from "/@/api/stuwork/dormroomstudent"
import { putObj } from '/@/api/recruit/newstucheckin'
import { useDict } from '/@/hooks/dict'
import { getDicts } from '/@/api/admin/dict'
import { getDataByRoomNo } from '/@/api/stuwork/dormroom'
const { sexy:genderData ,yes_no_type:yesOrNoData} = useDict('sexy','yes_no_type')

// Emits
const emit = defineEmits<{
  (e: 'reload', page: any): void
}>()

// 消息提示
const message = useMessage()

// 表单引用
const formRef = ref()

// 响应式数据
const page = ref<any>({})
const newStuCheckInDialog = ref(false)
const bedNoData = ref<any[]>([])
const roomNoList = ref<any[]>([])
const checkInStatusData = ref<any[]>([])
const loading = ref(false)
const isRoomTab = ref(false)
const bedNoKey = ref(0) // 用于强制更新床号选择器



const submitLoading = ref(false)

const form = reactive({
  name: "",
  checkInStatus: "",
  gender: "",
  idNumber: "",
  isRoom: "",
  roomNo: "",
  bedNo: "",
  remarks: "",
  residenceDetail: "",
  parentName: "",
  parentTelOne: "",
  parentTelTwo: ""
})

const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: ["blur", "change"] }
  ],
  gender: [
    { required: true, message: '请输入性别', trigger: ["blur", "change"] }
  ],
  idNumber: [
    { required: true, message: '请输入身份证号', trigger: ["blur", "change"] }
  ],
  checkInStatus: [
    { required: true, message: '请输入报到状态', trigger: ["blur", "change"] }
  ],
  isRoom: [
    { required: true, message: '请选择是否住宿', trigger: ["blur", "change"] }
  ],
  roomNo: [
    { required: true, message: '请选择宿舍号', trigger: ["blur", "change"] }
  ],
  bedNo: [
    { required: true, message: '请选择床位号', trigger: ["blur", "change"] }
  ],
}

// 监听报到状态变化
watch(() => form.checkInStatus, (newVal) => {
  if (newVal === '1') {
    isRoomTab.value = true
  } else {
    isRoomTab.value = false
  }
})

// 监听宿舍号变化
watch(() => form.roomNo, (newVal) => {
  console.log(newVal)
  if (newVal) {
    fearchRoomStuNums(newVal)
  }
})

// 监听是否住宿变化
watch(() => form.isRoom, (newVal) => {
  if (newVal === '0') {
    form.roomNo = ''
    form.bedNo = ''
  }
})

// 初始化表单
const initForm = () => {
  form.name = ""
  form.checkInStatus = ""
  form.gender = ""
  form.idNumber = ""
  form.isRoom = ""
  form.roomNo = ""
  form.bedNo = ""
  form.remarks = ""
  form.residenceDetail = ""
  form.parentName = ""
  form.parentTelOne = ""
  form.parentTelTwo = ""
}

// 初始化方法
const init = (formData: any, pageData: any) => {
  initForm()
  page.value = pageData
  submitLoading.value = false
  newStuCheckInDialog.value = true

  Object.assign(form, formData)
  if (formData.roomNo) {
    remoteMethod(formData.roomNo)
    fearchRoomStuNums(formData.bedNo)
  }
  getDicts('check_in_status').then(data => {
    checkInStatusData.value = data.data
  })
}

// 报到提交
const checkIn = () => {
  submitLoading.value = true
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      putObj(form).then(() => {
        message.success('报到成功')
        emit('reload', page.value)
        newStuCheckInDialog.value = false
        submitLoading.value = false
      }).catch(() => {
        submitLoading.value = false
      })
    } else {
      submitLoading.value = false
      return false
    }
  })
}

// 实时检索宿舍号
const remoteMethod = (query: string) => {
  if (query != '' && query.length >= 3) {
    const data = { 'roomNo': query }
    loading.value = true
    getDataByRoomNo(data).then(data => {
      roomNoList.value = data.data
      loading.value = false
    }).catch(() => {
      loading.value = false
    })
  }
}

// 查询此房间为几人间
const fearchRoomStuNums = (roomNo: string) => {
  fearchRoomStuNum(roomNo).then(data => {
    bedNoData.value = data.data
  })
}

// 判断床位是否禁用
const isRoomDisable = (notBedNo: any) => {
  if (undefined != notBedNo && "" != notBedNo) {
    return true
  } else {
    return false
  }
}

// 宿舍号变化时清空床号
const handleRoomNoChange = () => {
  form.bedNo = ''
  bedNoKey.value++ // 强制更新床号选择器
}

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

<style scoped>

</style>
