图书馆小程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

844 lines
23 KiB

<template>
<view class="booking-detail">
<view class="section">
<view class="calendar-wrap">
<view class="calendar-top">
<text class="calendar-title">选择入馆日期</text>
<text class="calendar-month">{{ displayYear }}.{{ String(displayMonth).padStart(2,'0') }}</text>
</view>
<view class="calendar-days-grid">
<view
v-for="(day, index) in calendarDays"
:key="index"
class="day-card"
:class="{
'card-selected': day.date === selectedDate,
'card-available': day.available && !day.tempClose && !day.userHasBooked,
'card-disabled': !day.available || day.tempClose,
'card-today': day.isToday,
'card-user-booked': day.userHasBooked,
'card-temp-close': day.tempClose
}"
@click="selectDate(day)"
>
<!-- 今天蓝色角标 -->
<view v-if="day.isToday" class="corner-block-today"></view>
<!-- 用户已预约 橙色角标 -->
<view v-if="day.userHasBooked" class="corner-block-booked"></view>
<text class="card-week">{{ day.isToday ? '今天' : day.weekText }}</text>
<text class="card-num">{{ day.day }}</text>
<text class="card-status">
{{ day.tempClose ? '闭馆' : (day.userHasBooked ? '已预约' : (day.available ? '可预约' : '')) }}
</text>
</view>
</view>
</view>
</view>
<!-- 时间选择:闭馆时整体禁用 -->
<view class="section" :class="{disabled: isSelectCloseDay}">
<view class="section-title">时间选择</view>
<view class="time-slots">
<view
v-for="slot in timeSlots"
:key="slot.id"
class="time-item"
:class="{
'selected': selectedTimeList.includes(slot.time),
disabled: isSelectCloseDay,
'booked-item': slot.isUserBooked
}"
@click="selectTime(slot)"
>
<!-- 这里由 slot.time 改为 slot.displayText -->
<text class="time-text">{{ slot.displayText }}</text>
<text v-if="slot.isUserBooked" class="booked-tag">已预约</text>
<uni-icons
v-if="selectedTimeList.includes(slot.time) && !slot.isUserBooked"
style="position: absolute; right: 5px; top: 50%; transform: translateY(-50%);"
custom-prefix="iconfont"
type="icon-xuanze"
size="20"
color="#01a4fe"
></uni-icons>
</view>
</view>
<view v-if="isSelectCloseDay" class="disable-tip">该日期闭馆,不可选择时间段</view>
</view>
<!-- 闭馆公告板块:仅选中闭馆日期显示 -->
<view v-if="isSelectCloseDay" class="section notice-section">
<view class="notice-title">闭馆公告</view>
<view class="notice-content">{{ closeNoticeText }}</view>
</view>
<view class="section operate-desc">
<view class="section-title" style="font-size: 14px;">预约说明</view>
<view class="desc-item">
<text class="color-blue">1、<text>蓝色</text>日期 可预约</text>
</view>
<view class="desc-item">
<text class="color-orange">2、<text>橙色</text>日期 已有预约</text>
</view>
<view class="desc-item">
<text class="color-gray">3、<text>灰色</text>日期 超出可选范围不可点击预约</text>
</view>
<view class="desc-item">
<text class="color-close">4、标<text>“闭馆”</text>日期 可查看公告,但无法预约或入馆</text>
</view>
<view class="desc-item">
<text>5、已预约时间段仅可查看,不可取消,可新增其他时间段</text>
</view>
</view>
<view class="bottom-bar">
<button class="btn-primary" :disabled="isSelectCloseDay" @click="confirmBooking">确认预约</button>
</view>
</view>
</template>
<script>
import { FetchInitLibraryReservationSettings, FetchInitMyReservation,FetchReserve } from '@/api/reservation';
import { getOpenId } from '@/utils/storage';
import config from '@/utils/config';
export default {
data() {
return {
selectedDate: '',
selectedTimeList: [], // 多选时间段数组
calendarDays: [],
timeSlots: [],
reserveConfig: null,
// 馆员临时闭馆日期列表,格式'2026-08-20',后台接口返回
tempCloseDateList: [],
// 闭馆公告映射 key:日期 value:公告内容
tempCloseNoticeMap: {},
// 用户已经预约过的日期列表,后台接口返回
userBookedDateList: [],
// key:日期字符串,value:已预约时间段,后端返回
userBookedMap:{}
};
},
computed: {
// 是否选中闭馆日期
isSelectCloseDay(){
if(!this.selectedDate) return false
return this.tempCloseDateList.includes(this.selectedDate)
},
// 获取当前闭馆公告文本
closeNoticeText(){
return this.tempCloseNoticeMap[this.selectedDate] || "本日场馆闭馆,暂不支持预约。"
},
displayYear() {
let targetDateStr = this.selectedDate;
if (!targetDateStr && this.calendarDays.length > 0) {
const firstValid = this.calendarDays.find(d => d.available && !d.tempClose) || this.calendarDays[0];
targetDateStr = firstValid.date;
}
if (!targetDateStr) return new Date().getFullYear();
const d = new Date(targetDateStr);
return d.getFullYear();
},
displayMonth() {
let targetDateStr = this.selectedDate;
if (!targetDateStr && this.calendarDays.length > 0) {
const firstValid = this.calendarDays.find(d => d.available && !d.tempClose) || this.calendarDays[0];
targetDateStr = firstValid.date;
}
if (!targetDateStr) return new Date().getMonth() + 1;
const d = new Date(targetDateStr);
return d.getMonth() + 1;
}
},
async onLoad(options) {
await this.initReservationSettings();
await this.initMyReservation();
if(this.reserveConfig){
this.generateCalendar();
}
},
methods: {
formatShowTime(timeStr){
return timeStr === '00:00 - 23:59' ? '全天' : timeStr
},
// 时间戳转 YYYY‑MM‑DD
formatTsToDate(ts) {
const d = new Date(ts);
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${y}-${m}-${day}`;
},
/**
* 将闭馆起止毫秒时间戳,展开成每一天日期字符串数组
* @param {number} startTs closureStartDate
* @param {number} endTs closureEndDate
* @returns string[] ['2026‑08‑01','2026‑08‑02']
*/
expandClosureRange(startTs, endTs){
const result = []
let cur = new Date(startTs)
const end = new Date(endTs)
// 只比对日期,去掉时分秒干扰
cur.setHours(0,0,0,0)
end.setHours(0,0,0,0)
while(cur <= end){
result.push(this.formatTsToDate(cur.getTime()))
cur.setDate(cur.getDate() + 1)
}
return result
},
// 把 HH:mm:ss 截取为 HH:mm
formatTimeHm(timeStr) {
if(!timeStr) return ''
return timeStr.substring(0,5)
},
// 初始化我的预约
async initMyReservation() {
try {
const openId = await getOpenId();
const res = await FetchInitMyReservation({
libcode: config.LIB_CODE,
openId: openId
})
console.log('初始化我的预约',res)
if(res.code === 200 && res.data){
// 闭馆
this.tempCloseDateList = []
this.tempCloseNoticeMap = {}
// 处理闭馆公告 vxLibraryClosureNotices
const closureList = Array.isArray(res.data.vxLibraryClosureNotices) ? res.data.vxLibraryClosureNotices : []
closureList.forEach(notice=>{
const dayArr = this.expandClosureRange(notice.closureStartDate, notice.closureEndDate)
dayArr.forEach(dateStr=>{
if(!this.tempCloseDateList.includes(dateStr)){
this.tempCloseDateList.push(dateStr)
}
// 同一个日期多条公告,用换行拼接;覆盖也可以看业务需求
if(this.tempCloseNoticeMap[dateStr]){
this.tempCloseNoticeMap[dateStr] += '\n\n' + notice.content
}else{
this.tempCloseNoticeMap[dateStr] = notice.content
}
})
})
// ==========处理用户预约 myReservation==========
this.userBookedDateList = []
this.userBookedMap = {}
const myRes = Array.isArray(res.data.myReservation) ? res.data.myReservation : []
myRes.forEach(item=>{
// specificDate 毫秒时间戳
const dateStr = this.formatTsToDate(item.specificDate)
const startHm = this.formatTimeHm(item.startTime)
const endHm = this.formatTimeHm(item.endTime)
const timeSlotText = `${startHm} - ${endHm}`
if(!this.userBookedMap[dateStr]){
this.userBookedMap[dateStr] = []
}
this.userBookedMap[dateStr].push(timeSlotText)
})
// 收集已预约日期
this.userBookedDateList = Object.keys(this.userBookedMap)
}
} catch (e) {
console.error('获取我的预约异常', e)
}
},
transformReserveConfig(apiData){
const { baseSetting, weekJson } = apiData;
const weekKeyMap = {
1: 'monday',
2: 'tuesday',
3: 'wednesday',
4: 'thursday',
5: 'friday',
6: 'saturday',
7: 'sunday'
};
const weekDays = [];
for(let wId=1;wId<=7;wId++){
const propName = weekKeyMap[wId];
const checked = !!baseSetting[propName];
const timeArr = weekJson[wId] || [];
// 把startTime[h,m], endTime[h,m]转 "HH:mm - HH:mm"
const times = timeArr.map(item=>{
const sh = String(item.startTime[0]).padStart(2,'0');
const sm = String(item.startTime[1]).padStart(2,'0');
const eh = String(item.endTime[0]).padStart(2,'0');
const em = String(item.endTime[1]).padStart(2,'0');
return `${sh}:${sm} - ${eh}:${em}`;
})
weekDays.push({
id:wId,
name:this.getWeekText(wId),
checked: checked,
times: times,
showPicker: false,
newTime: ""
})
}
return {
frequency: String(baseSetting.advanceBookingDays),
weekDays
}
},
// 初始化预约设置
async initReservationSettings() {
try {
const res = await FetchInitLibraryReservationSettings({
libcode: config.LIB_CODE
})
if (res && res.code === 200 && res.data) {
this.reserveConfig = this.transformReserveConfig(res.data);
}else{
console.error('初始化预约设置失败',res)
}
} catch (e) {
console.error('获取预约设置异常', e)
}
},
getWeekNum(dateStr) {
const d = new Date(dateStr);
const day = d.getDay();
return day === 0 ? 7 : day
},
getWeekText(weekNo){
const map = {1:'周一',2:'周二',3:'周三',4:'周四',5:'周五',6:'周六',7:'周日'}
return map[weekNo]
},
generateCalendar() {
if(!this.reserveConfig) return;
const today = new Date();
const todayStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
const freq = Number(this.reserveConfig.frequency);
const allowDateList = [];
for(let i = 0; i < freq; i++){
const temp = new Date(today);
temp.setDate(today.getDate() + i);
const ds = `${temp.getFullYear()}-${String(temp.getMonth()+1).padStart(2,'0')}-${String(temp.getDate()).padStart(2,'0')}`
allowDateList.push(ds)
}
const list = []
allowDateList.forEach(dateStr=>{
const weekNo = this.getWeekNum(dateStr)
const weekCfg = this.reserveConfig.weekDays.find(w => w.id === weekNo)
const available = !!weekCfg?.checked
const d = new Date(dateStr)
const tempClose = this.tempCloseDateList.includes(dateStr)
const userHasBooked = this.userBookedDateList.includes(dateStr)
list.push({
day: d.getDate(),
date: dateStr,
weekText: this.getWeekText(weekNo),
available: available,
isToday: dateStr === todayStr,
tempClose: tempClose,
userHasBooked: userHasBooked
})
})
this.calendarDays = list
// 找第一个不是闭馆的有效日期作为初始选中
const firstAvail = this.calendarDays.find(d => d.available && !d.tempClose);
if(firstAvail){
this.selectedDate = firstAvail.date
this.refreshTimeSlots(this.selectedDate)
}else{
this.selectedDate = ''
this.timeSlots = []
}
},
refreshTimeSlots(dateStr){
if(!dateStr) {
this.timeSlots = []
return
}
const weekNo = this.getWeekNum(dateStr)
const weekCfg = this.reserveConfig.weekDays.find(w => w.id === weekNo)
if(!weekCfg || !weekCfg.checked){
this.timeSlots = []
return
}
// 当前日期已经预约的时间段
const bookedTimeArr = this.userBookedMap[dateStr] || []
this.timeSlots = weekCfg.times.map((t, idx)=>{
// 判断是否全天
const displayText = t === '00:00 - 23:59' ? '全天' : t
return {
id: idx + 1,
time: t, // 原始时间字符串,用于选中判断、提交,不变
displayText, // 页面渲染展示文本
available: true,
isUserBooked: bookedTimeArr.includes(t)
}
})
// 回填历史已预约时间段,不能取消
this.selectedTimeList = [...bookedTimeArr]
},
selectDate(day) {
// 普通不可选(非临时闭馆):弹提示,禁止选中
if (!day.available && !day.tempClose) {
uni.showToast({
title: '超出可选的时间范围,请选择其他日期',
icon: 'none'
})
return;
}
// 临时闭馆 || 正常可预约:允许选中
this.selectedDate = day.date;
this.refreshTimeSlots(day.date);
},
selectTime(slot) {
if(this.isSelectCloseDay) return
if (!slot.available) return;
// 已预约时间段禁止取消
if(slot.isUserBooked){
uni.showToast({
title:"该时间段已预约,不可操作取消",
icon:"none"
})
return
}
const idx = this.selectedTimeList.indexOf(slot.time)
if(idx > -1){
// 本次新增的,可以取消
this.selectedTimeList.splice(idx,1)
}else{
this.selectedTimeList.push(slot.time)
}
},
async confirmBooking() {
if(this.isSelectCloseDay){
uni.showToast({title:"该日期闭馆,无法预约",icon:"none"})
return
}
if (!this.selectedDate) {
uni.showToast({ title: '请选择日期', icon: 'none' });
return;
}
const bookedTimeArr = this.userBookedMap[this.selectedDate] || []
// 过滤:只取本次新增勾选的时间段
const newSelectTimes = this.selectedTimeList.filter(item=> !bookedTimeArr.includes(item))
if (!newSelectTimes || newSelectTimes.length === 0) {
uni.showToast({ title: '请选择需要新增预约的时间段', icon: 'none' });
return;
}
uni.showLoading({ title: '预约中...' });
const openId = await getOpenId();
if (!openId) {
uni.hideLoading();
uni.showToast({ title: '获取用户openid失败', icon: 'none' });
return;
}
// 组装数组参数,后端接收对象数组
const param = newSelectTimes.map(timeStr => {
const [startPart, endPart] = timeStr.split(' - ');
const startTime = startPart.trim() + ':00';
const endTime = endPart.trim() + ':00';
return {
libcode: config.LIB_CODE, // 馆代码
openid: openId, // 用户微信OpenID
specificDate: this.selectedDate, // 预约日期
startTime: startTime, // 预约开始时间
endTime: endTime // 预约结束时间
}
})
try {
const res = await FetchReserve(param);
uni.hideLoading();
if(res.code === 200){
// 更新本地预约状态
if(!this.userBookedDateList.includes(this.selectedDate)){
this.userBookedDateList.push(this.selectedDate)
}
const old = this.userBookedMap[this.selectedDate] || []
this.userBookedMap[this.selectedDate] = [...new Set([...old,...newSelectTimes])]
const timeText = newSelectTimes.map(t=>this.formatShowTime(t)).join('\n');
uni.showModal({
title: '预约成功',
content: `您已新增预约\n日期:${this.selectedDate}\n时间段:${timeText}`,
showCancel: false,
confirmText: '确定',
success: async () => {
// 重新拉取我的预约数据(里面同时拉闭馆公告)
await this.initMyReservation();
// 重新生成日历
this.generateCalendar();
// 重新刷新当前选中日期的时间段
if(this.selectedDate){
this.refreshTimeSlots(this.selectedDate);
}
}
})
}else{
uni.showToast({ title: res.msg || '预约失败,请重试', icon: 'none' })
}
} catch (err) {
uni.hideLoading();
console.error('预约接口异常', err);
uni.showToast({ title: '预约失败,请重试', icon: 'none' })
}
}
}
};
</script>
<style lang="scss" scoped>
.booking-detail {
min-height: 100vh;
background-color: #f5f5f5;
padding-bottom: 70px;
}
.section {
background-color: #fff;
margin: 10px;
border-radius: 12px;
padding: 16px;
}
// 闭馆公告板块
.notice-section{
background:#FCECE9;
.notice-title{
font-size:15px;
font-weight:bold;
color:#FD7359;
margin-bottom:8px;
}
.notice-content{
font-size:14px;
color:#595959;
line-height:1.6;
}
}
// 时间板块整体置灰
.section.disabled{
opacity:0.55;
pointer-events:none;
}
.disable-tip{
margin-top:12px;
font-size:13px;
color:#999;
text-align:center;
}
.calendar-wrap{
background:#ffffff;
border-radius:16px;
}
.calendar-top{
display:flex;
justify-content:space-between;
align-items:center;
margin-bottom:12px;
}
.calendar-title{
font-size:17px;
font-weight:bold;
color:#222;
}
.calendar-month{
font-size:16px;
color:#333;
font-weight:bold;
}
.calendar-days-grid{
display:flex;
flex-wrap:wrap;
gap:8px;
}
.day-card{
width: calc((100% - 48px) / 7);
background:#f7f8fa;
border-radius: 4px;
padding: 4px 0;
display:flex;
flex-direction:column;
align-items:center;
justify-content:flex-start;
position:relative;
overflow: hidden;
}
/* 今天左上角蓝色三角 */
.corner-block-today{
position:absolute;
top:0;
left:0;
width: 0;
height: 0;
border-top: 12px solid #01a4fe;
border-right: 12px solid transparent;
}
/* 已预约 橙色三角角标 */
.corner-block-booked{
position:absolute;
top:0;
left:0;
width: 0;
height: 0;
border-top: 12px solid #ff7800;
border-right: 12px solid transparent;
}
.card-week{
font-size:12px;
color:#666;
margin-bottom:4px;
}
.card-num{
font-size:18px;
font-weight:bold;
color:#333;
}
.card-status{
font-size:11px;
margin-top:4px;
}
/* 可预约 */
.day-card.card-available{
background:#e8f4fd;
}
.day-card.card-available .card-status{
color:#01a4fe;
}
/* 闭馆/不可选 */
.day-card.card-disabled{
background:#f7f8fa;
}
.day-card.card-disabled .card-week,
.day-card.card-disabled .card-num,
.day-card.card-disabled .card-status{
color:#999;
}
/* 选中状态 */
.day-card.card-selected{
background:#01a4fe;
}
.day-card.card-selected .card-week,
.day-card.card-selected .card-num,
.day-card.card-selected .card-status{
color:#ffffff;
}
.day-card.card-user-booked{
background:#FFF3E5;
}
.day-card.card-user-booked .card-week,
.day-card.card-user-booked .card-num,
.day-card.card-user-booked .card-status{
color:#ff7800;
}
.day-card.card-user-booked.card-selected{
background:#ff7800;
}
.day-card.card-user-booked.card-selected .card-week,
.day-card.card-user-booked.card-selected .card-num,
.day-card.card-user-booked.card-selected .card-status{
color:#fff;
}
.day-card.card-temp-close .card-status{
color:#999;
}
.day-card.card-temp-close.card-selected {
background:#888;
}
.day-card.card-temp-close.card-selected .card-week,
.day-card.card-temp-close.card-selected .card-num,
.day-card.card-temp-close.card-selected .card-status{
color:#fff;
}
/* 时间选择 */
.section-title {
font-size: 16px;
font-weight: bold;
color: #333;
margin-bottom: 16px;
}
.time-slots {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.time-item {
position: relative;
width: calc(50% - 5px);
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px;
background-color: #f8f8f8;
border-radius: 8px;
border: 1px solid transparent;
}
.time-item.selected {
background-color: #e8f4fd;
border-color: #01a4fe;
}
.time-item.disabled{
pointer-events:none;
}
.time-item.booked-item{
background: #fff3e5;
border:1px solid #ffb870;
.time-text{
color:#ff7800;
}
}
.booked-tag{
font-size:11px;
color:#ff7800;
}
.time-text {
font-size: 14px;
color: #333;
}
.available-badge {
font-size: 12px;
color: #01a4fe;
background-color: #e8f4fd;
padding: 2px 8px;
border-radius: 10px;
}
.unavailable-badge {
font-size: 12px;
color: #999;
background-color: #f0f0f0;
padding: 2px 8px;
border-radius: 10px;
}
/* 底部按钮 */
.bottom-bar {
position: fixed;
bottom: 0;
left: 0;
right: 0;
padding: 10px;
background-color: #fff;
box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.1);
}
.btn-primary {
width: 100%;
height: 44px;
line-height: 44px;
background-color: #01a4fe;
color: #fff;
border-radius: 22px;
font-size: 15px;
border: none;
}
.btn-primary::after {
border: none;
}
.btn-primary[disabled]{
background:#b8d8f5 !important;
}
.operate-desc{
margin:10px;
padding:16px;
border-radius:12px;
background:#fff;
.section-title{
margin-bottom:10px !important;
}
.desc-item{
line-height:2;
font-size:13px;
}
.color-blue{
text{
color:#01a4fe;
}
}
.color-orange{
text{
color:#ff7800;
}
}
.color-gray{
text{
color:#999;
}
}
.color-close{
text{
color:#FD7359;
font-weight:500;
}
}
}
</style>