<template>
<div class="schedule">
<table>
<thead>
<tr>
<th></th>
<th v-for="room in rooms" :key="room.id">{{ room.name }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(timeSlot, index) in timeSlots" :key="index">
<td>{{ timeSlot.time }}</td>
<td
v-for="room in rooms"
:key="room.id"
@click="handleCellClick(room.id, timeSlot.time)"
>
<div :class="{ 'selected': isSelected(room.id, timeSlot.time) }"></div>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
rooms: [
{ id: 1, name: 'A', selectedTimeSlots: [] },
{ id: 2, name: 'B', selectedTimeSlots: [] },
{ id: 3, name: 'C', selectedTimeSlots: [] },
{ id: 4, name: 'D', selectedTimeSlots: [] },
{ id: 5, name: 'E', selectedTimeSlots: [] }
],
timeSlots: [],
};
},
mounted() {
this.generateTimeSlots();
},
methods: {
generateTimeSlots() {
const startTime = 8;
const endTime = 18;
const interval = 2;
for (let i = startTime; i < endTime - interval; i += interval) {
const timeSlot = { time: `${i}:00 - ${i + interval}:00` };
this.timeSlots.push(timeSlot);
}
},
handleCellClick(roomId, time) {
const selectedRoom = this.rooms.find(room => room.id === roomId);
if (this.isValidSelection(selectedRoom, time)) {
if (selectedRoom.selectedTimeSlots.includes(time)) {
selectedRoom.selectedTimeSlots = selectedRoom.selectedTimeSlots.filter(slot => slot !== time);
} else {
selectedRoom.selectedTimeSlots.push(time);
}
this.rooms.forEach(room => {
if (room.id !== roomId) {
room.selectedTimeSlots = [];
}
});
console.log('时间段:', time);
const selectedRooms = this.rooms
.filter(room => room.selectedTimeSlots.length > 0)
.map(room => room.name);
console.log('选中的教室:', selectedRooms.join(', '));
} else {
console.log('选择失败,时间段不连续');
}
},
isSelected(roomId, time) {
const selectedRoom = this.rooms.find(room => room.id === roomId);
return selectedRoom.selectedTimeSlots.includes(time);
},
isValidSelection(room, time) {
const selectedSlots = room.selectedTimeSlots;
if (selectedSlots.length === 0) {
return true;
}
const lastSelected = selectedSlots[selectedSlots.length - 1];
const [lastStart, lastEnd] = lastSelected.split(' - ');
const [currentStart, currentEnd] = time.split(' - ');
return lastEnd === currentStart;
},
isMerged(roomId, index) {
const selectedRoom = this.rooms.find(room => room.id === roomId);
const selectedTimeSlots = selectedRoom.selectedTimeSlots.map(timeSlot => timeSlot.time);
if (selectedTimeSlots.includes(this.timeSlots[index].time) && selectedTimeSlots.includes(this.timeSlots[index + 1].time)) {
return true;
}
return false;
},
}
};
</script>
<style scoped>
.schedule {
display: flex;
flex-direction: column;
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
border: 1px solid #dddddd;
text-align: center;
padding: 5px;
width: 44px;
height: 44px;
}
.selected {
background-color: lightblue;
cursor: pointer;
width: 100%;
height: 100%;
}
</style>