<template>
  <div class="room-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-select v-model="queryForm.building" placeholder="全部楼宇" clearable style="width: 140px">
                <el-option label="北区1号楼" value="1" />
                <el-option label="北区2号楼" value="2" />
                <el-option label="南区A栋" value="3" />
                <el-option label="南区B栋" value="4" />
              </el-select>
            </el-form-item>
            <el-form-item label="房间号">
              <el-input v-model="queryForm.roomNo" placeholder="例如：302" clearable style="width: 120px" 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="empty" />
                <el-option label="未满" value="partial" />
                <el-option label="满员" value="full" />
                <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="handleAdd">
            <vab-icon icon="add-line" class="icon-btn" /> 新增房间
          </el-button>
          <el-button type="success" @click="handleImport">
            <vab-icon icon="upload-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="fullNo" label="房间编号" width="140" sortable fixed />
        <el-table-column prop="buildingName" label="所属楼宇" width="120" />
        <el-table-column prop="floor" label="楼层" width="80" align="center" />
        <el-table-column prop="type" label="房间类型" width="120" />
        <el-table-column prop="gender" label="住宿性别" width="100" align="center">
          <template #default="{ row }">
             <vab-icon 
              :icon="row.gender === 'male' ? 'men-line' : 'women-line'" 
              :class="['gender-icon', row.gender === 'male' ? 'text-primary' : 'text-danger']" 
            />
            {{ row.gender === 'male' ? '男生' : '女生' }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="住宿费(元/年)" width="120" align="right">
          <template #default="{ row }">¥ {{ row.price }}</template>
        </el-table-column>
        <el-table-column label="入住情况" min-width="150">
          <template #default="{ row }">
            <div class="occupancy-bar">
              <el-progress 
                :percentage="row.occupancyPercentage" 
                :format="() => `${row.occupied}/${row.capacity}`"
                :status="getOccupancyStatus(row)"
              />
            </div>
          </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="200" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" text size="small" @click="handleEdit(row)">
              <vab-icon icon="edit-line" class="icon-sm" /> 编辑
            </el-button>
            <el-button type="info" text size="small" @click="handleViewStudents(row)">
              <vab-icon icon="group-line" class="icon-sm" /> 成员
            </el-button>
            <el-popconfirm title="确定删除该房间吗？" @confirm="handleDelete(row)">
              <template #reference>
                <el-button type="danger" text size="small">
                  <vab-icon icon="delete-bin-line" class="icon-sm" /> 删除
                </el-button>
              </template>
            </el-popconfirm>
          </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>

    <!-- 编辑/新增弹窗 -->
    <room-edit-dialog
      ref="roomEditDialogRef"
      @success="handleQuery"
    />

    <!-- 成员详情弹窗 -->
    <room-students-dialog
      ref="roomStudentsDialogRef"
    />
  </div>
</template>

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

defineOptions({
  name: 'RoomList',
})

const loading = ref(false)
const total = ref(100)
const tableData = ref([])
const roomEditDialogRef = ref()
const roomStudentsDialogRef = ref()

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

// --- Helpers ---
const getStatusLabel = (status) => {
  const map = { empty: '空闲', partial: '未满', full: '满员', maintenance: '维修', reserved: '预留' }
  return map[status] || status
}
const getStatusType = (status) => {
  const map = { empty: 'success', partial: 'primary', full: 'danger', maintenance: 'warning', reserved: 'info' }
  return map[status]
}
const getOccupancyStatus = (row) => {
  if (row.status === 'full') return 'exception'
  if (row.status === 'empty') return 'success'
  return ''
}

// --- Mock Data ---
const generateMockData = () => {
  const list = []
  const buildings = ['一号书院', '二号书院', '三号书院', '四号书院']
  
  for (let i = 0; i < 10; i++) {
    const buildingIdx = Math.floor(Math.random() * 4)
    const floor = Math.floor(Math.random() * 6) + 1
    const roomNum = Math.floor(Math.random() * 20) + 1
    const roomNo = `${roomNum.toString().padStart(2, '0')}`
    const fullNo = `${buildings[buildingIdx]}-${floor}${roomNo}`
    
    const capacity = 4
    const occupied = Math.floor(Math.random() * 5)
    let status = 'partial'
    if (occupied === 0) status = 'empty'
    else if (occupied === capacity) status = 'full'
    
    // 偶尔出现维修
    if (Math.random() > 0.9) {
      status = 'maintenance'
    }

    list.push({
      id: i + 1,
      buildingName: buildings[buildingIdx],
      buildingId: (buildingIdx + 1).toString(),
      floor: floor,
      roomNo: roomNo,
      fullNo: fullNo,
      type: '四人间',
      gender: Math.random() > 0.5 ? 'male' : 'female',
      price: 1200,
      capacity: capacity,
      occupied: status === 'maintenance' ? 0 : occupied,
      occupancyPercentage: status === 'maintenance' ? 0 : (occupied / capacity) * 100,
      status: status
    })
  }
  return list
}

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

const handleAdd = () => {
  roomEditDialogRef.value.open()
}

const handleEdit = (row) => {
  roomEditDialogRef.value.open(row)
}

const handleDelete = (row) => {
  ElMessage.success('删除成功')
  handleQuery()
}

const handleImport = () => {
  ElMessage.info('批量导入功能待开发')
}

const handleViewStudents = (row) => {
  // Mock students
  if (row.occupied === 0) {
    ElMessage.warning('该房间当前无人入住')
    return
  }
  
  roomStudentsDialogRef.value.open(row)
}

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

handleQuery()
</script>

<style lang="scss" scoped>
.room-list-container {
  .text-primary { color: var(--el-color-primary); }
  .text-danger { color: var(--el-color-danger); }
  .ml-10 { margin-left: 10px; }
  
  .occupancy-bar {
    width: 100%;
  }

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

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