<template>
  <vab-dialog
    :model-value="modelValue"
    :title="title"
    width="600px"
    @update:model-value="$emit('update:modelValue', $event)"
  >
    <div v-if="data" class="room-detail">
      <el-descriptions border :column="2">
        <el-descriptions-item label="房间号">{{ data.no }}</el-descriptions-item>
        <el-descriptions-item label="所属楼宇">{{ buildingName }}</el-descriptions-item>
        <el-descriptions-item label="房间类型">{{ data.category }}</el-descriptions-item>
        <el-descriptions-item label="住宿性别">
          <el-tag size="small" :type="data.type === 'male' ? '' : 'danger'">
            {{ data.type === 'male' ? '男生宿舍' : '女生宿舍' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="当前电量">124.5 kWh</el-descriptions-item>
        <el-descriptions-item label="最后抄表">2023-10-24 12:00</el-descriptions-item>
      </el-descriptions>

      <div class="mt-20">
        <div class="section-title">床位信息</div>
        <el-table :data="data.beds" style="width: 100%" border>
          <el-table-column prop="no" label="床位号" width="100" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag size="small" :type="row.status === 'occupied' ? 'success' : 'info'">
                {{ row.status === 'occupied' ? '已入住' : '空闲' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="student" label="入住学生">
             <template #default="{ row }">
              <div v-if="row.student" class="student-info">
                <span>{{ row.student.name }}</span>
                <span class="text-gray ml-5">({{ row.student.id }})</span>
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button 
                v-if="row.status === 'empty'" 
                type="primary" 
                size="small" 
                link 
                @click="handleCheckIn(row)"
              >
                入住
              </el-button>
              <el-button 
                v-else 
                type="danger" 
                size="small" 
                link 
                @click="handleCheckOut(row)"
              >
                退宿
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 入住办理弹窗 -->
    <el-dialog
      v-model="checkInVisible"
      title="办理入住"
      width="400px"
      append-to-body
    >
      <el-form :model="checkInForm" label-width="80px">
        <el-form-item label="床位号">
          <strong>{{ currentBed?.no }}</strong>
        </el-form-item>
        <el-form-item label="学生">
          <el-select 
            v-model="checkInForm.studentId" 
            placeholder="请输入学号/姓名搜索" 
            filterable 
            remote 
            :remote-method="searchStudent"
            :loading="searchLoading"
          >
            <el-option
              v-for="item in studentOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="checkInVisible = false"> <vab-icon icon="close" /> 取消</el-button>
        <el-button type="primary" @click="confirmCheckIn"> <vab-icon icon="check" /> 下一步</el-button>
      </template>
    </el-dialog>

    <!-- 完整入住流程 -->
    <check-in-dialog ref="checkInDialogRef" @success="handleCheckInSuccess" />

    <!-- 退宿结算流程 -->
    <check-out-settlement-dialog ref="checkOutSettlementRef" @success="handleCheckOutSuccess" />
  </vab-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import CheckInDialog from '/@/views/StudentManagement/CheckIn/components/CheckInDialog.vue'
import CheckOutSettlementDialog from './CheckOutSettlementDialog.vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '房间详情'
  },
  data: {
    type: Object,
    default: () => null
  },
  buildingName: {
    type: String,
    default: ''
  }
})

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

// --- Check In Logic ---
const checkInDialogRef = ref()
const checkOutSettlementRef = ref()
const checkInVisible = ref(false)
const currentBed = ref(null)
const searchLoading = ref(false)
const studentOptions = ref([])
const checkInForm = reactive({
  studentId: ''
})

const handleCheckIn = (bed) => {
  currentBed.value = bed
  checkInForm.studentId = ''
  studentOptions.value = []
  checkInVisible.value = true
}

const searchStudent = (query) => {
  if (query) {
    searchLoading.value = true
    setTimeout(() => {
      searchLoading.value = false
      studentOptions.value = [
        { value: '31901005', label: '苑国波 (31901005)', name: '苑国波', id: '31901005', gender: '男', college: 'ZJE', major: '生物医学' },
        { value: '31901006', label: '曹青青 (31901006)', name: '曹青青', id: '31901006', gender: '女', college: 'ZIBS', major: '金融科技' },
        { value: '31901007', label: '石焕然 (31901007)', name: '石焕然', id: '31901007', gender: '男', college: 'ZJUI', major: '电子工程' },
      ]
    }, 200)
  } else {
    studentOptions.value = []
  }
}

const confirmCheckIn = () => {
  if (!checkInForm.studentId) {
    ElMessage.warning('请选择入住学生')
    return
  }
  
  const student = studentOptions.value.find(i => i.value === checkInForm.studentId)
  checkInVisible.value = false
  
  // Open the detailed CheckInDialog
  checkInDialogRef.value.open({
    ...student,
    preAssigned: `待分配 ${currentBed.value.no}`
  })
}

const handleCheckInSuccess = (student) => {
  if (currentBed.value) {
    currentBed.value.status = 'occupied'
    currentBed.value.student = {
      id: student.id,
      name: student.name
    }
  }
  emit('refresh')
}

const handleCheckOut = (bed) => {
  // Use the new Settlement Dialog instead of simple confirm
  checkOutSettlementRef.value.open({
    student: bed.student,
    bed: bed,
    roomNo: props.data?.no
  })
}

const handleCheckOutSuccess = ({ bedId }) => {
  // Update bed status in the list
  const bed = props.data.beds.find(b => b.no === bedId || b === bedId) // Check how bedId matches
  // Actually, handleCheckOut passed the 'bed' object, so we can probably find it by object ref or ID
  // But let's look at the structure.
  // data.beds is passed from parent.
  
  // Since we don't have a reliable ID for bed in the simple mock in parent, 
  // let's just refresh everything.
  emit('refresh')
}
</script>

<style lang="scss" scoped>
.mt-20 {
  margin-top: 20px;
}

.text-gray {
  color: #909399;
}

.ml-5 {
  margin-left: 5px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 15px;
  border-left: 4px solid var(--el-color-primary);
  padding-left: 10px;
}
</style>
