<template>
  <el-drawer
    v-model="visible"
    title="集中住宿批次明细"
    size="60%"
    destroy-on-close
  >
    <div class="batch-info mb-20">
      <el-descriptions border :column="2">
        <el-descriptions-item label="批次名称">{{ currentBatch?.batchName }}</el-descriptions-item>
        <el-descriptions-item label="当前状态">
          <el-tag :type="getStatusType(currentBatch?.status)">{{ getStatusLabel(currentBatch?.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="集中时间">{{ currentBatch?.timeRange }}</el-descriptions-item>
        <el-descriptions-item label="涉及人数">{{ currentBatch?.studentCount }} 人</el-descriptions-item>
        <el-descriptions-item label="集中区域" :span="2">{{ currentBatch?.area }}</el-descriptions-item>
      </el-descriptions>
    </div>

    <div class="filter-container mb-10 flex justify-between">
      <div class="left-panel">
        <el-input
          v-model="queryForm.keyword"
          placeholder="姓名/学号/宿舍号"
          style="width: 200px"
          clearable
          @clear="handleQuery"
          @keyup.enter="handleQuery"
        >
          <template #append>
            <el-button type="primary" size="small" @click="handleQuery"> <vab-icon icon="search-line" /> </el-button>
          </template>
        </el-input>
        <el-select v-model="queryForm.status" placeholder="入住状态" clearable style="width: 120px" class="ml-10" @change="handleQuery">
          <el-option label="待入住" value="pending" />
          <el-option label="已入住" value="checked_in" />
          <el-option label="已搬回" value="returned" />
        </el-select>
      </div>
      <div class="right-panel">
        <el-button type="primary" plain @click="handleExport"> <vab-icon icon="download-line" /> 导出名单</el-button>
      </div>
    </div>

    <el-table v-loading="loading" :data="tableData" border stripe height="calc(100vh - 300px)">
      <el-table-column prop="name" label="姓名" width="100" />
      <el-table-column prop="studentId" label="学号" width="120" />
      <el-table-column prop="gender" label="性别" width="70" />
      <el-table-column prop="college" label="学院" width="120" />
      <el-table-column prop="originalRoom" label="原宿舍" width="120" />
      <el-table-column prop="allocatedRoom" label="集中宿舍" width="120">
        <template #default="{ row }">
          <span class="text-primary font-bold">{{ row.allocatedRoom }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getItemStatusType(row.status)">{{ getItemStatusLabel(row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="cardStatus" label="门禁卡" width="100">
        <template #default="{ row }">
          <el-tag :type="row.cardStatus === 'synced' ? 'success' : 'info'" effect="plain">
            {{ row.cardStatus === 'synced' ? '已同步' : '待同步' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
           <el-button 
            v-if="row.status === 'pending' && currentBatch?.status === 'active'" 
            type="primary" 
            link 
            size="small" 
            @click="handleCheckIn(row)"
          >
          <vab-icon icon="check-line"  />
            办理入住
          </el-button>
          <el-button 
            v-if="row.cardStatus !== 'synced' && currentBatch?.status === 'active'" 
            type="warning" 
            link 
            size="small" 
            @click="handleSyncCard(row)"
          >
            <vab-icon icon="sync-line" />
            写卡同步
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container mt-10 text-right">
       <el-pagination
        v-model:current-page="queryForm.pageNo"
        v-model:page-size="queryForm.pageSize"
        :total="total"
        layout="total, prev, pager, next"
        @current-change="handlePageChange"
      />
    </div>
  </el-drawer>
</template>

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

const visible = ref(false)
const currentBatch = ref(null)
const loading = ref(false)
const tableData = ref([])
const total = ref(0)

const queryForm = reactive({
  keyword: '',
  status: '',
  pageNo: 1,
  pageSize: 20
})

const getStatusLabel = (status) => {
  const map = { active: '集中住宿中', restored: '已还原', processing: '处理中' }
  return map[status]
}
const getStatusType = (status) => {
  const map = { active: 'success', restored: 'info', processing: 'warning' }
  return map[status]
}

const getItemStatusLabel = (status) => {
  const map = { pending: '待入住', checked_in: '已入住', returned: '已搬回' }
  return map[status]
}
const getItemStatusType = (status) => {
  const map = { pending: 'info', checked_in: 'success', returned: 'warning' }
  return map[status]
}

const open = (row) => {
  currentBatch.value = row
  visible.value = true
  handleQuery()
}

const handleQuery = () => {
  loading.value = true
  // Mock data based on batch ID
  setTimeout(() => {
    const mockList = [
      { id: 1, name: '梁健', studentId: '31901001', gender: '男', college: 'ZJE', originalRoom: '1-302-1', allocatedRoom: '2-101-1', status: 'checked_in', cardStatus: 'synced' },
      { id: 2, name: '鲁永波', studentId: '31901002', gender: '男', college: 'ZJUI', originalRoom: '2-405-2', allocatedRoom: '2-101-2', status: 'checked_in', cardStatus: 'synced' },
      { id: 3, name: '王应哲', studentId: '31901003', gender: '男', college: 'ZIBS', originalRoom: '1-202-3', allocatedRoom: '2-101-3', status: 'pending', cardStatus: 'pending' },
      { id: 4, name: '张三', studentId: '31901004', gender: '男', college: 'ZJE', originalRoom: '1-305-1', allocatedRoom: '2-102-1', status: 'pending', cardStatus: 'pending' },
      { id: 5, name: '李四', studentId: '31901005', gender: '男', college: 'ZJUI', originalRoom: '2-301-2', allocatedRoom: '2-102-2', status: 'checked_in', cardStatus: 'synced' },
    ]
    
    // Filter mock
    let filtered = mockList
    if (queryForm.keyword) {
      filtered = filtered.filter(item => item.name.includes(queryForm.keyword) || item.studentId.includes(queryForm.keyword))
    }
    if (queryForm.status) {
      filtered = filtered.filter(item => item.status === queryForm.status)
    }

    tableData.value = filtered
    total.value = filtered.length
    loading.value = false
  }, 300)
}

const handlePageChange = (val) => {
  queryForm.pageNo = val
  handleQuery()
}

const handleExport = () => {
  ElMessage.success('正在导出名单...')
}

const handleCheckIn = (row) => {
  row.status = 'checked_in'
  ElMessage.success(`${row.name} 办理入住成功`)
}

const handleSyncCard = (row) => {
  // Simulate card writing
  const loadingMsg = ElMessage.loading({
    message: '正在写入门禁权限...',
    duration: 0
  })
  setTimeout(() => {
    loadingMsg.close()
    row.cardStatus = 'synced'
    ElMessage.success('门禁权限同步成功')
  }, 1000)
}

defineExpose({
  open
})
</script>

<style lang="scss" scoped>
.mb-20 { margin-bottom: 20px; }
.mb-10 { margin-bottom: 10px; }
.mt-10 { margin-top: 10px; }
.ml-10 { margin-left: 10px; }
.text-right { text-align: right; }
.flex { display: flex; }
.justify-between { justify-content: space-between; }
.text-primary { color: var(--el-color-primary); }
.font-bold { font-weight: bold; }
</style>
