<template>
  <div class="bed-list-container">
    <vab-card>
      <vab-query-form>
        <vab-query-form-left-panel>
          <el-form :inline="true" :model="queryForm" @submit.prevent>
            <el-form-item label="宿舍号">
              <el-input v-model="queryForm.roomNo" placeholder="楼宇/房间号" clearable prefix-icon="home-4-line" />
            </el-form-item>
            <el-form-item label="床位状态">
              <el-select v-model="queryForm.status" placeholder="全部" clearable style="width: 120px">
                <el-option label="已占用" value="occupied" />
                <el-option label="空闲" value="empty" />
                <el-option label="维修" value="maintenance" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">
                <vab-icon icon="search-line" class="icon-btn" /> 查询
              </el-button>
            </el-form-item>
          </el-form>
        </vab-query-form-left-panel>
        <vab-query-form-right-panel>
          <el-button type="primary" @click="handleExport">
            <vab-icon icon="download-line" class="icon-btn" /> 导出床位表
          </el-button>
        </vab-query-form-right-panel>
      </vab-query-form>

      <el-table v-loading="loading" :data="tableData" border stripe>
        <el-table-column prop="bedId" label="床位编号" width="150" sortable fixed />
        <el-table-column prop="buildingName" label="楼宇" width="120" />
        <el-table-column prop="roomNo" label="房间号" width="100" />
        <el-table-column prop="bedNo" label="床号" width="80" align="center" />
        <el-table-column prop="type" label="床位类型" width="100">
          <template #default="{ row }">
            {{ row.type === 'upper' ? '上铺' : '下铺' }}
          </template>
        </el-table-column>
        <el-table-column label="当前住户" min-width="200">
          <template #default="{ row }">
            <div v-if="row.student" class="student-info">
              <span class="font-bold">{{ row.student.name }}</span>
              <span class="text-gray ml-5">({{ row.student.id }})</span>
              <el-tag size="small" class="ml-5">{{ row.student.college }}</el-tag>
            </div>
            <span v-else class="text-gray">--</span>
          </template>
        </el-table-column>
        <el-table-column prop="checkInDate" label="入住时间" width="120">
           <template #default="{ row }">
            {{ row.student ? row.student.checkInDate : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button v-if="row.status === 'empty'" type="primary" text size="small" @click="handleAssign(row)">
              <vab-icon icon="user-add-line" class="icon-sm" /> 分配
            </el-button>
            <el-button v-if="row.status === 'occupied'" type="warning" text size="small" @click="handleDetail(row)">
              <vab-icon icon="file-list-line" class="icon-sm" /> 详情
            </el-button>
            <el-button v-if="row.status !== 'maintenance'" type="danger" text size="small" @click="handleMaintenance(row)">
              <vab-icon icon="tools-line" class="icon-sm" /> 报修
            </el-button>
            <el-button v-else type="success" text size="small" @click="handleRestore(row)">
              <vab-icon icon="check-line" class="icon-sm" /> 修复
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <vab-pagination
        :current-page="queryForm.pageNo"
        :page-size="queryForm.pageSize"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </vab-card>

    <!-- 分配弹窗 -->
    <bed-assign-dialog
      v-model="assignVisible"
      :data="currentBed"
      @success="handleQuery"
    />
  </div>
</template>

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

defineOptions({
  name: 'BedList',
})

const loading = ref(false)
const total = ref(100)
const tableData = ref([])
const assignVisible = ref(false)
const currentBed = ref(null)

const queryForm = reactive({
  roomNo: '',
  status: '',
  pageNo: 1,
  pageSize: 10,
})

const getStatusLabel = (status) => {
  const map = { occupied: '已占用', empty: '空闲', maintenance: '维修' }
  return map[status] || status
}
const getStatusType = (status) => {
  const map = { occupied: 'success', empty: 'info', maintenance: 'danger' }
  return map[status]
}

const generateMockData = () => {
  const list = []
  const buildings = ['一号书院', '二号书院', '三号书院']
  
  for (let i = 0; i < 10; i++) {
    const buildingIdx = Math.floor(Math.random() * 3)
    const room = `${Math.floor(Math.random() * 6 + 1)}0${Math.floor(Math.random() * 9 + 1)}`
    const bedNo = (i % 4) + 1
    const isOccupied = Math.random() > 0.3
    
    list.push({
      bedId: `BED-${(i+1).toString().padStart(6, '0')}`,
      buildingName: buildings[buildingIdx],
      roomNo: room,
      bedNo: bedNo,
      type: bedNo % 2 === 0 ? 'upper' : 'lower',
      status: isOccupied ? 'occupied' : 'empty',
      student: isOccupied ? {
        name: `学生${i+1}`,
        id: `319010${i+1}`,
        college: 'ZJUI',
        checkInDate: '2025-09-01'
      } : null
    })
  }
  return list
}

const handleQuery = () => {
  loading.value = true
  setTimeout(() => {
    tableData.value = generateMockData()
    loading.value = false
  }, 500)
}

const handleExport = () => {
  ElMessage.success('导出成功')
}

const handleAssign = (row) => {
  currentBed.value = row
  assignVisible.value = true
}

const handleDetail = (row) => {
  ElMessage.info(`查看 ${row.student.name} 的住宿详情`)
}

const handleMaintenance = (row) => {
  row.status = 'maintenance'
  ElMessage.warning('已标记为维修状态')
}

const handleRestore = (row) => {
  row.status = 'empty'
  ElMessage.success('已恢复为空闲状态')
}

const handleCurrentChange = (val) => {
  queryForm.pageNo = val
  handleQuery()
}
const handleSizeChange = (val) => {
  queryForm.pageSize = val
  handleQuery()
}

handleQuery()
</script>

<style lang="scss" scoped>
.bed-list-container {
  .text-gray { color: #909399; }
  .ml-5 { margin-left: 5px; }
  .font-bold { font-weight: bold; }

  .icon-btn {
    margin-right: 6px;
    font-size: 16px;
    vertical-align: middle;
  }
  
  .icon-sm {
    margin-right: 4px;
    font-size: 14px;
    vertical-align: middle;
  }
}
</style>