<template>
  <div class="function-room-container">
    <el-row :gutter="20">
      <!-- 左侧房间列表 -->
      <el-col :span="6">
        <vab-card title="功能房列表" class="room-list-card">
          <div class="room-list">
            <div 
              v-for="room in roomList" 
              :key="room.id" 
              class="room-item"
              :class="{ active: currentRoom?.id === room.id }"
              @click="handleRoomClick(room)"
            >
              <el-image :src="room.image" class="room-img" fit="cover" />
              <div class="info">
                <div class="name">{{ room.name }}</div>
                <div class="desc">容量: {{ room.capacity }}人 | 设备: {{ room.equipment }}</div>
                <div class="status">
                  <el-tag size="small" :type="room.status === 'open' ? 'success' : 'danger'">
                    {{ room.status === 'open' ? '开放中' : '维护中' }}
                  </el-tag>
                </div>
              </div>
            </div>
          </div>
        </vab-card>
      </el-col>

      <!-- 右侧预约日历与审批 -->
      <el-col :span="18">
        <vab-card>
          <el-tabs v-model="activeTab">
            <el-tab-pane label="预约视图" name="calendar">
              <div class="calendar-header mb-20">
                <div class="title">{{ currentRoom?.name || '请选择功能房' }} - 预约情况</div>
                <div class="actions">
                  <el-date-picker v-model="currentDate" type="date" placeholder="选择日期" :disabled-date="disabledDate" />
                  <el-select v-model="duration" style="width: 120px" class="ml-10" @change="handleDurationChange" placeholder="时长">
                    <el-option label="30分钟" :value="30" />
                    <el-option label="60分钟" :value="60" />
                    <el-option label="90分钟" :value="90" />
                    <el-option label="120分钟" :value="120" />
                  </el-select>
                  <el-button type="primary" class="ml-10" @click="handleReserve" :disabled="!currentRoom || currentRoom.status !== 'open'">
                    新增预约
                  </el-button>
                </div>
              </div>

              <div v-if="currentRoom" class="time-slots">
                <div 
                  v-for="(slot, index) in timeSlots" 
                  :key="index" 
                  class="slot-item"
                  :class="getSlotClass(slot)"
                >
                  <div class="time">{{ slot.time }}</div>
                  <div class="status-text">{{ getSlotStatusText(slot) }}</div>
                  <div v-if="slot.booking" class="user-info">
                    {{ slot.booking.userName }}
                  </div>
                </div>
              </div>
              <el-empty v-else description="请先在左侧选择一个功能房" />
            </el-tab-pane>

            <el-tab-pane label="审批列表" name="approval">
              <el-table :data="approvalList" border stripe>
                <el-table-column prop="roomName" label="预约房间" width="150" />
                <el-table-column prop="userName" label="申请人" width="120" />
                <el-table-column prop="timeRange" label="使用时间" min-width="200" />
                <el-table-column prop="reason" label="用途" show-overflow-tooltip />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="{ row }">
                    <el-tag :type="getApprovalStatusType(row.status)">{{ getApprovalStatusLabel(row.status) }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                  <template #default="{ row }">
                    <div v-if="row.status === 'pending'">
                      <el-button type="success" size="small" @click="handleApprove(row)">通过</el-button>
                      <el-button type="danger" size="small" @click="handleReject(row)">驳回</el-button>
                    </div>
                    <span v-else class="text-gray text-xs">已处理</span>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </vab-card>
      </el-col>
    </el-row>

    <!-- 预约申请弹窗 -->
    <room-reserve-dialog ref="reserveDialogRef" @success="handleReserveSuccess" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import RoomReserveDialog from './components/RoomReserveDialog.vue'

defineOptions({
  name: 'FunctionRoom',
})

// --- Data ---
const activeTab = ref('calendar')
const currentDate = ref(new Date())
const currentRoom = ref<any>(null)
const reserveDialogRef = ref()
const duration = ref(30)

const roomList = ref([
  { id: 1, name: '研讨室 A101', capacity: 10, equipment: '投影仪, 白板', status: 'open', image: 'https://picsum.photos/100/100?random=10' },
  { id: 2, name: '舞蹈房 B202', capacity: 20, equipment: '音响, 镜墙', status: 'open', image: 'https://picsum.photos/100/100?random=11' },
  { id: 3, name: '琴房 C305', capacity: 2, equipment: '钢琴', status: 'maintenance', image: 'https://picsum.photos/100/100?random=12' },
  { id: 4, name: '多功能厅', capacity: 100, equipment: '舞台, 音响', status: 'open', image: 'https://picsum.photos/100/100?random=13' },
])

// Helper
const formatTime = (minutes: number) => {
  const h = Math.floor(minutes / 60).toString().padStart(2, '0')
  const m = (minutes % 60).toString().padStart(2, '0')
  return `${h}:${m}`
}

// Mock Time Slots (08:00 - 22:00)
const generateSlots = () => {
  const slots = []
  const startMinutes = 8 * 60
  const endMinutes = 22 * 60
  
  for (let m = startMinutes; m < endMinutes; m += duration.value) {
    if (m + duration.value > endMinutes) break
    
    const time = `${formatTime(m)}-${formatTime(m + duration.value)}`

    // Random status
    const rand = Math.random()
    let booking = null
    let status = 'free'
    
    if (rand > 0.8) {
      status = 'booked'
      booking = { userName: '梁健' }
    } else if (rand > 0.7) {
      status = 'pending'
      booking = { userName: '鲁永波' }
    }

    slots.push({ time, status, booking })
  }
  return slots
}

const timeSlots = ref<any[]>([])

const handleDurationChange = () => {
  timeSlots.value = generateSlots()
}

const approvalList = ref([
  { id: 1, roomName: '舞蹈房 B202', userName: '曹青青', timeRange: '2026-01-24 18:00-20:00', reason: '排练校庆节目', status: 'pending' },
  { id: 2, roomName: '研讨室 A101', userName: '王应哲', timeRange: '2026-01-24 14:00-16:00', reason: '小组作业讨论', status: 'approved' },
  { id: 3, roomName: '琴房 C305', userName: '杨勇捷', timeRange: '2026-01-24 10:00-11:00', reason: '个人练习', status: 'rejected' },
])

// --- Computed ---
const availableSlots = computed(() => {
  return timeSlots.value.filter(s => s.status === 'free')
})

// --- Helpers ---
const getSlotClass = (slot: any) => {
  return {
    'free': slot.status === 'free',
    'booked': slot.status === 'booked',
    'pending': slot.status === 'pending'
  }
}

const getSlotStatusText = (slot: any) => {
  const map: any = { free: '空闲', booked: '已预订', pending: '审核中' }
  return map[slot.status]
}

const getApprovalStatusLabel = (status: string) => {
  const map: any = { pending: '待审批', approved: '已通过', rejected: '已驳回' }
  return map[status]
}
const getApprovalStatusType = (status: string) => {
  const map: any = { pending: 'warning', approved: 'success', rejected: 'danger' }
  return map[status]
}

// --- Methods ---
const handleRoomClick = (room: any) => {
  currentRoom.value = room
  // Refresh slots mock
  timeSlots.value = generateSlots()
}

const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7
}

const handleReserve = () => {
  reserveDialogRef.value.open(currentRoom.value, currentDate.value, availableSlots.value)
}

const handleReserveSuccess = (data: any) => {
  // Update mock view
  data.slots.forEach((time: string) => {
    const slot = timeSlots.value.find(s => s.time === time)
    if (slot) {
      slot.status = 'pending'
      slot.booking = { userName: data.userName }
    }
  })
}

const handleApprove = (row: any) => {
  row.status = 'approved'
  ElMessage.success('审批通过，门禁权限已自动下发')
}

const handleReject = (row: any) => {
  row.status = 'rejected'
  ElMessage.info('申请已驳回')
}

// Init
handleRoomClick(roomList.value[0])
</script>

<style lang="scss" scoped>
.function-room-container {
  .mb-20 { margin-bottom: 20px; }
  .ml-10 { margin-left: 10px; }
  .text-gray { color: #909399; }
  .text-xs { font-size: 12px; }

  .room-list-card {
    height: 600px;
    
    .room-list {
      .room-item {
        display: flex;
        padding: 10px;
        border: 1px solid #eee;
        border-radius: 8px;
        margin-bottom: 10px;
        cursor: pointer;
        transition: all 0.3s;
        
        &.active {
          border-color: var(--el-color-primary);
          background: var(--el-color-primary-light-9);
        }

        .room-img {
          width: 70px;
          height: 70px;
          border-radius: 4px;
          margin-right: 10px;
        }

        .info {
          flex: 1;
          .name { font-weight: bold; font-size: 14px; margin-bottom: 5px; }
          .desc { font-size: 12px; color: #666; margin-bottom: 5px; }
        }
      }
    }
  }

  .calendar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .title { font-size: 18px; font-weight: bold; border-left: 4px solid var(--el-color-primary); padding-left: 10px; }
  }

  .time-slots {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;

    .slot-item {
      width: 120px;
      height: 80px;
      border-radius: 8px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      border: 1px solid #dcdfe6;
      font-size: 13px;
      
      .time { font-weight: bold; margin-bottom: 5px; }
      .user-info { font-size: 12px; margin-top: 5px; }

      &.free {
        background: #f0f9eb;
        color: #67c23a;
        border-color: #b3e19d;
      }
      &.booked {
        background: #fef0f0;
        color: #f56c6c;
        border-color: #fab6b6;
        .user-info { color: #f56c6c; }
      }
      &.pending {
        background: #fdf6ec;
        color: #e6a23c;
        border-color: #f3d19e;
      }
    }
  }
}
</style>
