2080 lines
79 KiB
JavaScript
2080 lines
79 KiB
JavaScript
const planningApi = require('../../api/planning')
|
||
const productsApi = require('../../api/products')
|
||
const customersApi = require('../../api/customers')
|
||
const dateUtil = require('../../utils/date')
|
||
const { markPlanningRefresh } = require('../../utils/planning-refresh')
|
||
const { uploadObjectFile } = require('../../utils/upload')
|
||
const { showErrorToast, toUserMessage } = require('../../utils/toast')
|
||
const { showActionModal } = require('../../utils/action-modal')
|
||
|
||
const DRAFT_STORAGE_PREFIX = 'managerAppointmentDraft'
|
||
const DRAFT_TTL_MS = 7 * 24 * 60 * 60 * 1000
|
||
const DRAFT_SAVE_DELAY_MS = 400
|
||
const TIME_SLOT_MINUTES = 1
|
||
const MINUTE_VALUES = Array.from({ length: 60 }, (_, index) => index)
|
||
|
||
function buildClientRequestId(prefix) {
|
||
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
|
||
}
|
||
|
||
function getCalendarArtists(calendar) {
|
||
return calendar && Array.isArray(calendar.artists) ? calendar.artists : []
|
||
}
|
||
|
||
function findArtist(artists, artistId) {
|
||
return artists.find(item => String(item.id) === String(artistId)) || {}
|
||
}
|
||
|
||
function canCreateAppointment() {
|
||
const app = getApp()
|
||
const userInfo = app.globalData.userInfo || {}
|
||
return Number(userInfo.type) !== 3
|
||
}
|
||
|
||
function isShopManager() {
|
||
const userInfo = getApp().globalData.userInfo || {}
|
||
return Number(userInfo.type) === 2
|
||
}
|
||
|
||
function isShopBusinessExpired() {
|
||
const userInfo = getApp().globalData.userInfo || {}
|
||
return Number(userInfo.type) === 2 && userInfo.shopBusinessExpired === true
|
||
}
|
||
|
||
function showBusinessExpiryNotice(page) {
|
||
return showActionModal(page, {
|
||
title: '门店经营有效期已到期',
|
||
content: '当前门店暂不能新增普通预约。历史订单、查询和补录不受影响,请联系平台管理员办理续期。',
|
||
confirmText: '知道了'
|
||
}).then(() => {})
|
||
}
|
||
|
||
function buildDraftKey() {
|
||
const app = getApp()
|
||
const userInfo = app.globalData.userInfo || {}
|
||
return `${DRAFT_STORAGE_PREFIX}:${userInfo.id || 'guest'}:${userInfo.shopId || 'default'}`
|
||
}
|
||
|
||
function readDraft() {
|
||
try {
|
||
const draft = wx.getStorageSync(buildDraftKey())
|
||
if (!draft || !draft.form) return null
|
||
const savedAt = Number(draft.savedAt)
|
||
if (!Number.isFinite(savedAt) || savedAt <= 0 || savedAt > Date.now() || Date.now() - savedAt > DRAFT_TTL_MS) {
|
||
wx.removeStorageSync(buildDraftKey())
|
||
return null
|
||
}
|
||
return draft
|
||
} catch (error) {
|
||
throw new Error(`读取预约草稿失败:${error.message || error}`)
|
||
}
|
||
}
|
||
|
||
function writeDraftForm(form, artistSelectionId, durationManuallyChanged) {
|
||
try {
|
||
const savedAt = Date.now()
|
||
wx.setStorageSync(buildDraftKey(), {
|
||
form,
|
||
artistSelectionId: artistSelectionId === '__unassigned__' ? artistSelectionId : '',
|
||
durationManuallyChanged: Boolean(durationManuallyChanged),
|
||
savedAt
|
||
})
|
||
return savedAt
|
||
} catch (error) {
|
||
throw new Error(`保存预约草稿失败:${error.message || error}`)
|
||
}
|
||
}
|
||
|
||
function removeDraftForm() {
|
||
try {
|
||
wx.removeStorageSync(buildDraftKey())
|
||
} catch (error) {
|
||
throw new Error(`清空预约草稿失败:${error.message || error}`)
|
||
}
|
||
}
|
||
|
||
function formatDraftStatus(status, savedAt) {
|
||
if (!savedAt) return status
|
||
const date = new Date(Number(savedAt))
|
||
if (Number.isNaN(date.getTime())) return status
|
||
const pad = value => String(value).padStart(2, '0')
|
||
return `${status} · ${date.getMonth() + 1}月${date.getDate()}日 ${pad(date.getHours())}:${pad(date.getMinutes())}`
|
||
}
|
||
|
||
function decodeOptionValue(value) {
|
||
if (value === undefined || value === null) return ''
|
||
try {
|
||
return decodeURIComponent(String(value))
|
||
} catch (error) {
|
||
return String(value)
|
||
}
|
||
}
|
||
|
||
function hasDraftContent(form, entryDefaults, selectedArtist, defaultDuration) {
|
||
if (!form) return false
|
||
const changedDate = String(form.appointmentDate || '') !== String(entryDefaults.appointmentDate || '')
|
||
const currentArtistSelectionId = selectedArtist && selectedArtist.id === '__unassigned__'
|
||
? '__unassigned__'
|
||
: String(form.artistId || '')
|
||
const defaultArtistSelectionId = String(entryDefaults.artistSelectionId || entryDefaults.artistId || '')
|
||
const changedArtist = currentArtistSelectionId !== defaultArtistSelectionId
|
||
return Boolean(
|
||
form.customerUserId || form.customerName || form.phone || form.wechatId ||
|
||
form.productId || form.manualProductTitle || form.manualProductDescription ||
|
||
form.manualProductTags || form.manualProductTargetAudience || form.manualProductPrecautions ||
|
||
form.manualProductImageFileIds || (Array.isArray(form.manualProductImages) && form.manualProductImages.length) ||
|
||
String(form.amount || '').trim() || form.appointmentTime || form.createCustomerRecord || form.remark ||
|
||
changedDate || changedArtist ||
|
||
(Number(form.durationMinutes) > 0 && Number(form.durationMinutes) !== Number(defaultDuration || 60))
|
||
)
|
||
}
|
||
|
||
function normalizeManualProductImages(form) {
|
||
const savedImages = form && Array.isArray(form.manualProductImages) ? form.manualProductImages : null
|
||
if (savedImages) {
|
||
return savedImages.map(image => {
|
||
const fileUrl = image && (image.fileUrl || image.url) ? String(image.fileUrl || image.url) : ''
|
||
return {
|
||
fileId: image && image.fileId !== undefined ? String(image.fileId) : '',
|
||
fileUrl,
|
||
previewUrl: image && image.previewUrl ? String(image.previewUrl) : fileUrl
|
||
}
|
||
}).filter(image => image.fileId).slice(0, 9)
|
||
}
|
||
const fileIds = String(form && form.manualProductImageFileIds || '').split(',').map(fileId => fileId.trim()).filter(Boolean)
|
||
return fileIds.slice(0, 9).map((fileId, index) => ({
|
||
fileId,
|
||
fileUrl: index === 0 && form && form.manualProductImageUrl ? String(form.manualProductImageUrl) : '',
|
||
previewUrl: index === 0 && form && form.manualProductImageUrl ? String(form.manualProductImageUrl) : ''
|
||
}))
|
||
}
|
||
|
||
function buildManualProductImagePatch(images) {
|
||
const normalizedImages = (images || []).slice(0, 9)
|
||
return {
|
||
'form.manualProductImages': normalizedImages,
|
||
'form.manualProductImageFileIds': normalizedImages.map(image => image.fileId).filter(Boolean).join(','),
|
||
'form.manualProductImageUrl': normalizedImages[0] ? normalizedImages[0].previewUrl || normalizedImages[0].fileUrl || '' : ''
|
||
}
|
||
}
|
||
|
||
function chooseManualProductImagePaths(count) {
|
||
const normalizedCount = Math.min(9, Math.max(1, Math.floor(Number(count) || 1)))
|
||
return new Promise((resolve, reject) => {
|
||
wx.chooseMedia({
|
||
count: normalizedCount,
|
||
mediaType: ['image'],
|
||
sourceType: ['album', 'camera'],
|
||
sizeType: ['original'],
|
||
success(result) {
|
||
resolve((result.tempFiles || []).map(file => file && file.tempFilePath).filter(Boolean).slice(0, normalizedCount))
|
||
},
|
||
fail(error) {
|
||
const message = error && error.errMsg ? error.errMsg : ''
|
||
if (message.includes('cancel')) {
|
||
resolve([])
|
||
return
|
||
}
|
||
reject(new Error(`选择图片失败:${message || '未知错误'}`))
|
||
}
|
||
})
|
||
})
|
||
}
|
||
|
||
function normalizeDuration(value) {
|
||
const duration = Number(value)
|
||
return Number.isFinite(duration) && duration > 0 ? Math.floor(duration) : 0
|
||
}
|
||
|
||
function buildTimeRangeLabel(startMinute, durationMinutes) {
|
||
return `${dateUtil.timeFromMinutes(startMinute)}-${dateUtil.timeFromMinutes(startMinute + durationMinutes)}`
|
||
}
|
||
|
||
function getTimePeriod(minute) {
|
||
if (minute < 12 * 60) {
|
||
return { key: 'morning', title: '上午' }
|
||
}
|
||
if (minute < 18 * 60) {
|
||
return { key: 'afternoon', title: '下午' }
|
||
}
|
||
return { key: 'evening', title: '晚上' }
|
||
}
|
||
|
||
function normalizeAppointmentDate(item) {
|
||
return item.date || String(item.startTime || '').slice(0, 10)
|
||
}
|
||
|
||
function extractTimeText(value) {
|
||
const target = String(value || '')
|
||
if (target.includes('T')) {
|
||
return target.slice(11, 16)
|
||
}
|
||
if (target.includes(' ')) {
|
||
return target.slice(11, 16)
|
||
}
|
||
return target.slice(0, 5)
|
||
}
|
||
|
||
function resolveAppointmentStartMinute(item) {
|
||
if (item.startMinute !== undefined && item.startMinute !== null) {
|
||
return Number(item.startMinute)
|
||
}
|
||
return dateUtil.minutesOfDay(extractTimeText(item.startTime))
|
||
}
|
||
|
||
function resolveAppointmentEndMinute(item, startMinute) {
|
||
if (item.endMinute !== undefined && item.endMinute !== null) {
|
||
return Number(item.endMinute)
|
||
}
|
||
if (item.endTime) {
|
||
return dateUtil.minutesOfDay(extractTimeText(item.endTime))
|
||
}
|
||
return startMinute + Number(item.durationMinutes || 60)
|
||
}
|
||
|
||
function isCancelledAppointment(item) {
|
||
return item.status === 3 || item.statusText === '已取消'
|
||
}
|
||
|
||
function buildBusyRanges(appointments, form) {
|
||
return (appointments || [])
|
||
.filter(item => String(item.artistId) === String(form.artistId))
|
||
.filter(item => normalizeAppointmentDate(item) === form.appointmentDate)
|
||
.filter(item => !isCancelledAppointment(item))
|
||
.map(item => {
|
||
const startMinute = resolveAppointmentStartMinute(item)
|
||
return {
|
||
startMinute,
|
||
endMinute: resolveAppointmentEndMinute(item, startMinute)
|
||
}
|
||
})
|
||
}
|
||
|
||
function hasBusyConflict(startMinute, endMinute, ranges) {
|
||
return ranges.some(range => startMinute < range.endMinute && endMinute > range.startMinute)
|
||
}
|
||
|
||
function resolveBusinessHours(calendar, targetDate) {
|
||
const source = calendar || {}
|
||
const day = targetDate && (source.daySummaries || []).find(item => item.date === targetDate)
|
||
if (day) {
|
||
if (day.shopOpen === false) return { start: '', end: '', closed: true }
|
||
const dayStart = String(day.shopStartTime || '').trim()
|
||
const dayEnd = String(day.shopEndTime || '').trim()
|
||
if (/^\d{1,2}:[0-5]\d$/.test(dayStart) && /^\d{1,2}:[0-5]\d$/.test(dayEnd)
|
||
&& dateUtil.minutesOfDay(dayEnd) > dateUtil.minutesOfDay(dayStart)) return { start: dayStart, end: dayEnd }
|
||
}
|
||
const parts = String(source.businessHours || '').split('-')
|
||
const start = String(source.businessStartTime || parts[0] || '').trim()
|
||
const end = String(source.businessEndTime || parts[1] || '').trim()
|
||
const valid = value => {
|
||
if (!/^\d{1,2}:[0-5]\d$/.test(value)) return false
|
||
const hour = Number(value.split(':')[0])
|
||
return hour >= 0 && hour <= 23
|
||
}
|
||
if (!valid(start) || !valid(end) || dateUtil.minutesOfDay(end) <= dateUtil.minutesOfDay(start)) {
|
||
return { start: '', end: '' }
|
||
}
|
||
return { start, end }
|
||
}
|
||
|
||
function buildAvailableTimeGroups(calendar, form, durationMinutes) {
|
||
const schedules = (calendar.schedules || [])
|
||
.filter(item => String(item.artistId) === String(form.artistId))
|
||
.filter(item => item.date === form.appointmentDate)
|
||
.filter(item => item.status === 1 && Number(item.capacity === undefined ? 1 : item.capacity) >= 1)
|
||
const busyRanges = buildBusyRanges(calendar.appointments || [], form)
|
||
const today = dateUtil.formatDate(new Date())
|
||
const now = new Date()
|
||
const currentMinute = now.getHours() * 60 + now.getMinutes()
|
||
const businessHours = resolveBusinessHours(calendar, form.appointmentDate)
|
||
if (!businessHours.start) return []
|
||
const businessStart = dateUtil.minutesOfDay(businessHours.start)
|
||
const businessEnd = dateUtil.minutesOfDay(businessHours.end)
|
||
const groupMap = {
|
||
morning: { key: 'morning', title: '上午', times: [] },
|
||
afternoon: { key: 'afternoon', title: '下午', times: [] },
|
||
evening: { key: 'evening', title: '晚上', times: [] }
|
||
}
|
||
schedules.forEach(schedule => {
|
||
const scheduleStart = dateUtil.minutesOfDay(extractTimeText(schedule.startTime))
|
||
const scheduleEnd = dateUtil.minutesOfDay(extractTimeText(schedule.endTime))
|
||
for (let minute = scheduleStart; minute + durationMinutes <= scheduleEnd; minute += TIME_SLOT_MINUTES) {
|
||
if (minute < businessStart || minute + durationMinutes > businessEnd) continue
|
||
if (form.appointmentDate < today || (form.appointmentDate === today && minute <= currentMinute)) continue
|
||
const endMinute = minute + durationMinutes
|
||
if (!hasBusyConflict(minute, endMinute, busyRanges)) {
|
||
const period = getTimePeriod(minute)
|
||
groupMap[period.key].times.push({
|
||
value: dateUtil.timeFromMinutes(minute),
|
||
rangeText: buildTimeRangeLabel(minute, durationMinutes)
|
||
})
|
||
}
|
||
}
|
||
})
|
||
return Object.keys(groupMap)
|
||
.map(key => ({
|
||
...groupMap[key],
|
||
times: groupMap[key].times.filter((item, index, array) => array.findIndex(candidate => candidate.value === item.value) === index)
|
||
}))
|
||
.filter(group => group.times.length > 0)
|
||
}
|
||
|
||
function buildUnassignedTimeGroups(durationMinutes, businessStart, businessEnd, appointmentDate) {
|
||
const groupMap = {
|
||
morning: { key: 'morning', title: '上午', times: [] },
|
||
afternoon: { key: 'afternoon', title: '下午', times: [] },
|
||
evening: { key: 'evening', title: '晚上', times: [] }
|
||
}
|
||
if (!businessStart || !businessEnd) return []
|
||
const start = dateUtil.minutesOfDay(businessStart)
|
||
const end = dateUtil.minutesOfDay(businessEnd)
|
||
if (end <= start) return []
|
||
const now = new Date()
|
||
const today = dateUtil.formatDate(now)
|
||
const currentMinute = now.getHours() * 60 + now.getMinutes()
|
||
for (let minute = start; minute + durationMinutes <= end; minute += TIME_SLOT_MINUTES) {
|
||
if (appointmentDate && appointmentDate < today) continue
|
||
const period = getTimePeriod(minute)
|
||
groupMap[period.key].times.push({
|
||
value: dateUtil.timeFromMinutes(minute),
|
||
rangeText: buildTimeRangeLabel(minute, durationMinutes),
|
||
status: appointmentDate === today && minute <= currentMinute ? 'past' : 'available',
|
||
statusText: appointmentDate === today && minute <= currentMinute ? '已过时' : ''
|
||
})
|
||
}
|
||
return Object.keys(groupMap).map(key => groupMap[key]).filter(group => group.times.length > 0)
|
||
}
|
||
|
||
function flattenTimeGroups(groups) {
|
||
return (groups || []).reduce((list, group) => list.concat(group.times || []), [])
|
||
}
|
||
|
||
function buildTimeValues(durationMinutes, businessStart, businessEnd, appointmentDate) {
|
||
const values = []
|
||
if (!businessStart || !businessEnd) return values
|
||
const open = dateUtil.minutesOfDay(businessStart)
|
||
const close = dateUtil.minutesOfDay(businessEnd)
|
||
if (close <= open) return values
|
||
const now = new Date()
|
||
const today = dateUtil.formatDate(now)
|
||
const currentMinute = now.getHours() * 60 + now.getMinutes()
|
||
for (let minute = open; minute + durationMinutes <= close; minute += TIME_SLOT_MINUTES) {
|
||
if (appointmentDate && appointmentDate < today) continue
|
||
values.push({ value: dateUtil.timeFromMinutes(minute), past: appointmentDate === today && minute <= currentMinute })
|
||
}
|
||
return values
|
||
}
|
||
|
||
function buildTimePickerSlots(calendar, form, durationMinutes) {
|
||
const schedules = calendar.schedules || []
|
||
const busyRanges = form.artistId ? buildBusyRanges(calendar.appointments || [], form) : []
|
||
const businessHours = resolveBusinessHours(calendar, form.appointmentDate)
|
||
if (!businessHours.start) return []
|
||
const businessStart = businessHours.start
|
||
const businessEnd = businessHours.end
|
||
return buildTimeValues(durationMinutes, businessStart, businessEnd, form.appointmentDate).map(time => {
|
||
const value = time.value
|
||
const startMinute = dateUtil.minutesOfDay(value)
|
||
const endMinute = startMinute + durationMinutes
|
||
const occupied = hasBusyConflict(startMinute, endMinute, busyRanges)
|
||
const scheduled = !form.artistId || schedules.some(schedule =>
|
||
isScheduleCoveringTime(schedule, form, startMinute, endMinute)
|
||
)
|
||
const status = time.past ? 'past' : occupied ? 'occupied' : scheduled ? 'available' : 'off-shift'
|
||
return {
|
||
value,
|
||
hour: Number(value.slice(0, 2)),
|
||
minute: Number(value.slice(3, 5)),
|
||
rangeText: buildTimeRangeLabel(startMinute, durationMinutes),
|
||
status,
|
||
statusText: status === 'past' ? '已过时' : status === 'occupied' ? '已占用' : status === 'off-shift' ? '无排班' : ''
|
||
}
|
||
})
|
||
}
|
||
|
||
function buildTimePickerGroups(slots) {
|
||
const groupMap = {
|
||
morning: { key: 'morning', title: '上午', times: [] },
|
||
afternoon: { key: 'afternoon', title: '下午', times: [] },
|
||
evening: { key: 'evening', title: '晚上', times: [] }
|
||
}
|
||
;(slots || []).forEach(slot => groupMap[getTimePeriod(dateUtil.minutesOfDay(slot.value)).key].times.push(slot))
|
||
return Object.keys(groupMap).map(key => groupMap[key]).filter(group => group.times.length > 0)
|
||
}
|
||
|
||
function buildTimeWheelState(slots, preferredTime) {
|
||
if (!slots || slots.length === 0) {
|
||
return {
|
||
timePickerHours: [],
|
||
timePickerMinutes: [],
|
||
timePickerValue: [0, 0],
|
||
selectedTimeCandidate: '',
|
||
timePickerCandidateStatus: 'off-shift'
|
||
}
|
||
}
|
||
const preferredSlot = slots.find(slot => slot.value === preferredTime) || slots.find(slot => slot.value === '14:00')
|
||
const firstAvailableSlot = slots.find(slot => slot.status === 'available')
|
||
const selectedSlot = preferredSlot && preferredSlot.status === 'available'
|
||
? preferredSlot
|
||
: firstAvailableSlot || preferredSlot || slots[0]
|
||
const hours = Array.from(new Set(slots.map(slot => slot.hour)))
|
||
const selectedHourIndex = Math.max(0, hours.indexOf(selectedSlot.hour))
|
||
const minuteValues = MINUTE_VALUES
|
||
const minutes = minuteValues.map(minute => {
|
||
const slot = slots.find(item => item.hour === selectedSlot.hour && item.minute === minute)
|
||
return {
|
||
value: minute,
|
||
label: String(minute).padStart(2, '0'),
|
||
status: slot ? slot.status : 'off-shift',
|
||
disabled: !slot || slot.status !== 'available'
|
||
}
|
||
})
|
||
const selectedMinuteIndex = Math.max(0, minuteValues.indexOf(selectedSlot.minute))
|
||
return {
|
||
timePickerHours: hours.map(hour => ({
|
||
value: hour,
|
||
label: String(hour).padStart(2, '0'),
|
||
disabled: !slots.some(slot => slot.hour === hour && slot.status === 'available')
|
||
})),
|
||
timePickerMinutes: minutes,
|
||
timePickerValue: [selectedHourIndex, selectedMinuteIndex],
|
||
selectedTimeCandidate: selectedSlot.value,
|
||
timePickerCandidateStatus: selectedSlot.status
|
||
}
|
||
}
|
||
|
||
function timeWheelStateForHour(slots, hour, selectedMinute) {
|
||
const minuteValues = MINUTE_VALUES
|
||
const minutes = minuteValues.map(minute => {
|
||
const slot = slots.find(item => item.hour === hour && item.minute === minute)
|
||
return {
|
||
value: minute,
|
||
label: String(minute).padStart(2, '0'),
|
||
status: slot ? slot.status : 'off-shift',
|
||
disabled: !slot || slot.status !== 'available'
|
||
}
|
||
})
|
||
const selectedMinuteIndex = Math.max(0, minuteValues.indexOf(selectedMinute))
|
||
return { timePickerMinutes: minutes, selectedMinuteIndex }
|
||
}
|
||
|
||
function customerCreatedAt(customer) {
|
||
return customer.createTime || customer.createdAt || customer.addedAt || ''
|
||
}
|
||
|
||
function formatCustomerCreatedAt(value) {
|
||
if (!value) return '添加时间未知'
|
||
return `添加于 ${String(value).replace('T', ' ').slice(0, 16)}`
|
||
}
|
||
|
||
function parseProductTags(product) {
|
||
if (Array.isArray(product.tagList) && product.tagList.length > 0) {
|
||
return product.tagList
|
||
}
|
||
if (Array.isArray(product.tagInfos) && product.tagInfos.length > 0) {
|
||
return product.tagInfos.map(item => item.tagName).filter(Boolean)
|
||
}
|
||
return String(product.tags || '')
|
||
.split(/[;,,、]/)
|
||
.map(item => item.trim())
|
||
.filter(Boolean)
|
||
}
|
||
|
||
function normalizeProduct(product, artists) {
|
||
const imageUrls = Array.isArray(product.imageUrls) ? product.imageUrls : []
|
||
const bookableArtists = String(product.bookableArtists || '')
|
||
.split(',')
|
||
.map(item => item.trim())
|
||
.filter(Boolean)
|
||
const artistNames = bookableArtists
|
||
.map(id => findArtist(artists, id).name)
|
||
.filter(Boolean)
|
||
const durationText = product.approximateDuration || (product.serviceDurationMinutes ? `${product.serviceDurationMinutes}分钟` : '')
|
||
return {
|
||
...product,
|
||
coverImage: imageUrls[0] || '',
|
||
tagList: parseProductTags(product).slice(0, 4),
|
||
artistText: artistNames.length > 0 ? artistNames.join('、') : '全部美甲师',
|
||
priceText: product.price || product.price === 0 ? `¥${product.price}` : '价格待定',
|
||
durationText
|
||
}
|
||
}
|
||
|
||
function isScheduleCoveringTime(schedule, form, startMinute, endMinute) {
|
||
if (!schedule || String(schedule.artistId) !== String(form.artistId) || schedule.date !== form.appointmentDate) {
|
||
return false
|
||
}
|
||
if (schedule.status !== 1 || Number(schedule.capacity === undefined ? 1 : schedule.capacity) < 1) {
|
||
return false
|
||
}
|
||
const scheduleStartMinute = dateUtil.minutesOfDay(extractTimeText(schedule.startTime))
|
||
const scheduleEndMinute = dateUtil.minutesOfDay(extractTimeText(schedule.endTime))
|
||
return scheduleStartMinute <= startMinute && scheduleEndMinute >= endMinute
|
||
}
|
||
|
||
function normalizeCustomer(customer) {
|
||
const name = customer.nickname || customer.name || customer.account || ''
|
||
const phone = customer.contactPhone || customer.phone || ''
|
||
return {
|
||
id: customer.id,
|
||
name,
|
||
phone,
|
||
phoneAvailable: customer.phoneAvailable === true || (Boolean(phone) && !String(phone).includes('*')),
|
||
displayName: name || phone || '客户',
|
||
displayPhone: phone || '未填写手机号',
|
||
createdAt: customerCreatedAt(customer)
|
||
}
|
||
}
|
||
|
||
function buildCustomerSelectorItem(customer) {
|
||
return {
|
||
...customer,
|
||
title: customer.displayName,
|
||
subtitle: formatCustomerCreatedAt(customer.createdAt),
|
||
rightText: customer.displayPhone
|
||
}
|
||
}
|
||
|
||
function buildArtistSelectorItem(artist) {
|
||
return {
|
||
...artist,
|
||
title: artist.name || '未命名美甲师',
|
||
subtitle: artist.statusText || '可用于指定预约',
|
||
meta: artist.workStartTime && artist.workEndTime ? `${artist.workStartTime.slice(0, 5)}-${artist.workEndTime.slice(0, 5)}` : '',
|
||
avatar: artist.avatar || artist.avatarUrl || '/assets/images/default-user-avatar.png'
|
||
}
|
||
}
|
||
|
||
function buildAppointmentDateLabels(value) {
|
||
const dateValue = String(value || '')
|
||
if (!dateValue) {
|
||
return { day: '', badge: '请选择预约日期', long: '请选择预约日期' }
|
||
}
|
||
const date = new Date(dateValue.replace(/-/g, '/'))
|
||
if (Number.isNaN(date.getTime())) {
|
||
return { day: '', badge: dateValue, long: dateValue }
|
||
}
|
||
const today = dateUtil.formatDate(new Date())
|
||
const tomorrow = dateUtil.formatDate(dateUtil.addDays(new Date(), 1))
|
||
const dayLabel = dateValue === today
|
||
? '今天'
|
||
: dateValue === tomorrow
|
||
? '明天'
|
||
: `周${'日一二三四五六'[date.getDay()]}`
|
||
return {
|
||
day: dayLabel,
|
||
badge: `${dayLabel} · ${dateUtil.formatCnDate(dateValue)}`,
|
||
long: `${dayLabel} · ${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
|
||
}
|
||
}
|
||
|
||
Page({
|
||
data: {
|
||
form: {
|
||
customerUserId: '',
|
||
customerName: '',
|
||
phone: '',
|
||
appointmentDate: dateUtil.formatDate(new Date()),
|
||
appointmentTime: '',
|
||
amount: '',
|
||
productId: '',
|
||
manualProductTitle: '',
|
||
manualProductPrice: '',
|
||
manualProductDescription: '',
|
||
manualProductTags: '',
|
||
manualProductTargetAudience: '',
|
||
manualProductPrecautions: '',
|
||
manualProductImageFileIds: '',
|
||
manualProductImageUrl: '',
|
||
manualProductImages: [],
|
||
durationMinutes: '60',
|
||
wechatId: '',
|
||
artistId: '',
|
||
createCustomerRecord: false,
|
||
remark: ''
|
||
},
|
||
unifiedStyleDescription: '',
|
||
customerOptions: [],
|
||
customerDirectory: [],
|
||
businessStartTime: '',
|
||
businessEndTime: '',
|
||
defaultAppointmentDurationMinutes: 60,
|
||
durationManuallyChanged: false,
|
||
customerSheetVisible: false,
|
||
customerKeyword: '',
|
||
customerViewMode: 'list',
|
||
customerNewestFirst: true,
|
||
customerSuggestions: [],
|
||
customerLoading: false,
|
||
customerError: '',
|
||
products: [],
|
||
filteredProducts: [],
|
||
artists: [],
|
||
artistSelectorItems: [],
|
||
artistSheetVisible: false,
|
||
artistKeyword: '',
|
||
artistError: '',
|
||
selectedProduct: {},
|
||
selectedProductPriceText: '',
|
||
manualProductTitleLength: 0,
|
||
selectedArtist: {},
|
||
productModalVisible: false,
|
||
manualProductSheetVisible: false,
|
||
manualProductMoreVisible: false,
|
||
productKeyword: '',
|
||
productError: '',
|
||
loadingProducts: false,
|
||
conflictTip: '',
|
||
conflictLevel: 'free',
|
||
canCreateAppointment: true,
|
||
canManageShopSettings: false,
|
||
draftSavedAtText: '',
|
||
manualImageUploading: false,
|
||
timeSheetVisible: false,
|
||
timePickerMode: 'wheel',
|
||
timePickerValue: [0, 0],
|
||
timePickerHours: [],
|
||
timePickerMinutes: [],
|
||
timePickerSlots: [],
|
||
timePickerGroups: [],
|
||
timePickerCandidateStatus: 'off-shift',
|
||
selectedTimeCandidate: '',
|
||
timeLoading: false,
|
||
timeError: '',
|
||
businessHoursMissing: false,
|
||
timeSelectTip: '请先选择美甲师并填写时长',
|
||
appointmentDayLabel: '',
|
||
appointmentDateBadge: '',
|
||
appointmentDateLong: '',
|
||
availableTimeGroups: [],
|
||
loading: false
|
||
},
|
||
|
||
onLoad(options = {}) {
|
||
const manualDateMode = options && options.dateMode === 'manual'
|
||
const today = dateUtil.formatDate(new Date())
|
||
if (options && options.date && options.date < today) {
|
||
this._pendingHistoricalArtistId = options.artistId || ''
|
||
this.showBackfillPrompt(options.date, '所选日期已经过去')
|
||
return
|
||
}
|
||
const creatable = canCreateAppointment()
|
||
let draft = null
|
||
if (creatable) {
|
||
try {
|
||
draft = readDraft()
|
||
} catch (error) {
|
||
showErrorToast(error, '预约草稿读取失败')
|
||
}
|
||
}
|
||
const draftForm = draft && draft.form ? draft.form : {}
|
||
const routeDate = options && options.date ? String(options.date) : ''
|
||
const routeArtistSelectionId = options && options.artistId ? String(options.artistId) : ''
|
||
const routeArtistId = routeArtistSelectionId === '__unassigned__' ? '' : routeArtistSelectionId
|
||
const hasRouteCustomer = ['customerUserId', 'customerName', 'wechatId', 'phone']
|
||
.some(key => options && options[key] !== undefined)
|
||
const routeDateChanged = Boolean(routeDate && draftForm.appointmentDate && routeDate !== draftForm.appointmentDate)
|
||
const draftArtistSelectionId = draft && draft.artistSelectionId === '__unassigned__'
|
||
? '__unassigned__'
|
||
: String(draftForm.artistId || '')
|
||
const manualProductImages = normalizeManualProductImages(draftForm)
|
||
const appointmentDate = routeDate || draftForm.appointmentDate || (manualDateMode ? '' : today)
|
||
const appointmentTime = routeDateChanged ? '' : (draftForm.appointmentTime || '')
|
||
const dateLabels = buildAppointmentDateLabels(appointmentDate)
|
||
this._entryDefaults = {
|
||
appointmentDate: routeDate || (manualDateMode ? '' : today),
|
||
artistId: routeArtistId,
|
||
artistSelectionId: routeArtistSelectionId
|
||
}
|
||
this._draftReady = false
|
||
this._draftPersistenceDisabled = false
|
||
this._draftTimer = null
|
||
this.setData({
|
||
canCreateAppointment: creatable,
|
||
canManageShopSettings: isShopManager(),
|
||
form: {
|
||
...this.data.form,
|
||
...draftForm,
|
||
manualProductImages,
|
||
manualProductImageFileIds: manualProductImages.map(image => image.fileId).join(','),
|
||
manualProductImageUrl: manualProductImages[0] ? manualProductImages[0].previewUrl || manualProductImages[0].fileUrl : '',
|
||
customerUserId: hasRouteCustomer ? String(options.customerUserId || '') : (draftForm.customerUserId || ''),
|
||
customerName: hasRouteCustomer ? decodeOptionValue(options.customerName) : (draftForm.customerName || ''),
|
||
wechatId: hasRouteCustomer ? decodeOptionValue(options.wechatId) : (draftForm.wechatId || ''),
|
||
phone: hasRouteCustomer ? decodeOptionValue(options.phone) : (draftForm.phone || ''),
|
||
appointmentDate,
|
||
appointmentTime,
|
||
artistId: routeArtistId || draftForm.artistId || ''
|
||
},
|
||
selectedArtist: routeArtistSelectionId === '__unassigned__' || (!routeArtistId && draftArtistSelectionId === '__unassigned__')
|
||
? { id: '__unassigned__', name: '暂不分配美甲师' }
|
||
: {},
|
||
durationManuallyChanged: draft && draft.durationManuallyChanged !== undefined
|
||
? Boolean(draft.durationManuallyChanged)
|
||
: Boolean(draftForm.durationMinutes && !draftForm.productId && Number(draftForm.durationMinutes) !== 60),
|
||
manualProductTitleLength: String(draftForm.manualProductTitle || '').length,
|
||
unifiedStyleDescription: String(draftForm.remark || draftForm.manualProductDescription || ''),
|
||
draftSavedAtText: draft ? formatDraftStatus('已恢复草稿', draft.savedAt) : '内容变更后自动保存到本机,保留7天',
|
||
appointmentDayLabel: dateLabels.day,
|
||
appointmentDateBadge: dateLabels.badge,
|
||
appointmentDateLong: dateLabels.long
|
||
})
|
||
if (!creatable) {
|
||
wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' })
|
||
return
|
||
}
|
||
this.installDraftAutoSave()
|
||
this._draftReady = true
|
||
this.loadOptions()
|
||
},
|
||
|
||
onHide() {
|
||
this.flushDraftSave()
|
||
},
|
||
|
||
onShow() {
|
||
if (!this._refreshTimesAfterSettings) return
|
||
this._refreshTimesAfterSettings = false
|
||
this.refreshAvailableTimes()
|
||
},
|
||
|
||
openShopSettings() {
|
||
if (!this.data.canManageShopSettings) {
|
||
wx.showToast({ title: '请联系店长设置门店营业时间', icon: 'none' })
|
||
return
|
||
}
|
||
this._refreshTimesAfterSettings = true
|
||
wx.navigateTo({ url: '/pages/shop-settings/index' })
|
||
},
|
||
|
||
async loadOptions() {
|
||
this.setData({ loadingProducts: true })
|
||
try {
|
||
const productsData = await productsApi.list({ page: 1, size: 100 })
|
||
const products = productsData.list || productsData || []
|
||
this.setData({ products, productError: '' })
|
||
} catch (error) {
|
||
this.setData({
|
||
products: [],
|
||
filteredProducts: [],
|
||
productError: toUserMessage(error, '作品列表加载失败')
|
||
})
|
||
} finally {
|
||
this.setData({ loadingProducts: false })
|
||
}
|
||
await this.loadArtists()
|
||
this.refreshProductCards()
|
||
const selectedProduct = this.data.filteredProducts.find(item => String(item.id) === String(this.data.form.productId)) || {}
|
||
const selectedProductPatch = {
|
||
selectedProduct,
|
||
selectedProductPriceText: selectedProduct.priceText || '',
|
||
unifiedStyleDescription: this.data.unifiedStyleDescription || this.data.form.remark || this.data.form.manualProductDescription || '',
|
||
manualProductTitleLength: this.data.form.manualProductTitle
|
||
? String(this.data.form.manualProductTitle).length
|
||
: String(selectedProduct.title || '').length
|
||
}
|
||
if (selectedProduct.id && (this.data.form.amount === '' || this.data.form.amount === undefined)) {
|
||
selectedProductPatch['form.amount'] = selectedProduct.price === undefined || selectedProduct.price === null ? '' : String(selectedProduct.price)
|
||
}
|
||
this.setData(selectedProductPatch)
|
||
await this.refreshAvailableTimes()
|
||
this.checkAvailability()
|
||
},
|
||
|
||
async loadArtists(preferredArtistId, fallbackEmployee) {
|
||
const unassignedSelection = preferredArtistId === undefined && this.data.selectedArtist.id === '__unassigned__'
|
||
? this.data.selectedArtist
|
||
: {}
|
||
try {
|
||
const calendar = await planningApi.calendar({
|
||
startDate: this.data.form.appointmentDate || dateUtil.formatDate(new Date()),
|
||
endDate: this.data.form.appointmentDate || dateUtil.formatDate(new Date())
|
||
})
|
||
let artists = getCalendarArtists(calendar)
|
||
const businessHours = resolveBusinessHours(calendar, this.data.form.appointmentDate)
|
||
const defaultDuration = Number(calendar.defaultAppointmentDurationMinutes) || 60
|
||
const requestedId = preferredArtistId || this.data.form.artistId
|
||
if (fallbackEmployee && requestedId && !findArtist(artists, requestedId).id) {
|
||
artists = artists.concat({
|
||
id: requestedId,
|
||
name: fallbackEmployee.name || fallbackEmployee.title,
|
||
avatar: fallbackEmployee.avatar || ''
|
||
})
|
||
}
|
||
const selectedArtist = requestedId
|
||
? findArtist(artists, requestedId)
|
||
: unassignedSelection
|
||
this.setData({
|
||
businessStartTime: businessHours.start,
|
||
businessEndTime: businessHours.end,
|
||
defaultAppointmentDurationMinutes: defaultDuration,
|
||
...(!this.data.durationManuallyChanged && !this.data.form.productId && !this.data.form.appointmentTime
|
||
? { 'form.durationMinutes': String(defaultDuration) }
|
||
: {}),
|
||
artists,
|
||
artistSelectorItems: this.filterArtistItems(artists, this.data.artistKeyword),
|
||
selectedArtist,
|
||
artistError: '',
|
||
'form.artistId': selectedArtist.id === '__unassigned__' ? '' : selectedArtist.id || ''
|
||
})
|
||
this.refreshProductCards()
|
||
} catch (error) {
|
||
this.setData({
|
||
artists: [],
|
||
artistSelectorItems: this.filterArtistItems([], this.data.artistKeyword),
|
||
businessStartTime: '',
|
||
businessEndTime: '',
|
||
selectedArtist: unassignedSelection,
|
||
'form.artistId': '',
|
||
artistError: toUserMessage(error, '美甲师列表加载失败'),
|
||
conflictTip: toUserMessage(error, '美甲师列表加载失败'),
|
||
conflictLevel: 'danger'
|
||
})
|
||
}
|
||
},
|
||
|
||
async loadCustomerDirectory() {
|
||
this.setData({ customerLoading: true })
|
||
try {
|
||
const size = 100
|
||
const rows = []
|
||
let page = 1
|
||
let total = Number.POSITIVE_INFINITY
|
||
while (rows.length < total) {
|
||
const result = await customersApi.listForAppointment({ page, size })
|
||
const currentRows = Array.isArray(result) ? result : (result.list || [])
|
||
rows.push(...currentRows)
|
||
if (!Array.isArray(result) && Number.isFinite(Number(result.total))) {
|
||
total = Number(result.total)
|
||
} else if (currentRows.length < size) {
|
||
total = rows.length
|
||
}
|
||
if (currentRows.length === 0) break
|
||
page += 1
|
||
}
|
||
const directory = rows.map(normalizeCustomer)
|
||
this.setData({
|
||
customerDirectory: directory,
|
||
customerOptions: this.sortCustomerOptions(directory),
|
||
customerError: ''
|
||
})
|
||
this.refreshCustomerSuggestions(this.data.form.customerName, this.data.form.phone)
|
||
} catch (error) {
|
||
this.setData({ customerDirectory: [], customerOptions: [], customerError: toUserMessage(error, '客户列表加载失败') })
|
||
} finally {
|
||
this.setData({ customerLoading: false })
|
||
}
|
||
},
|
||
|
||
sortCustomerOptions(customers, newestFirst = this.data.customerNewestFirst) {
|
||
return (customers || []).slice().sort((left, right) => {
|
||
const leftDate = String(left.createdAt || '')
|
||
const rightDate = String(right.createdAt || '')
|
||
return newestFirst ? rightDate.localeCompare(leftDate) : leftDate.localeCompare(rightDate)
|
||
}).map(buildCustomerSelectorItem)
|
||
},
|
||
|
||
onInput(event) {
|
||
const field = event.currentTarget.dataset.field
|
||
const patch = {
|
||
[`form.${field}`]: event.detail.value
|
||
}
|
||
this.setData(patch)
|
||
if (field === 'durationMinutes') {
|
||
this.setData({ durationManuallyChanged: true })
|
||
this.refreshAvailableTimes()
|
||
this.checkAvailability()
|
||
}
|
||
},
|
||
|
||
onStyleTitleInput(event) {
|
||
const patch = {
|
||
'form.manualProductTitle': event.detail.value,
|
||
manualProductTitleLength: String(event.detail.value || '').length
|
||
}
|
||
if (this.data.form.productId) {
|
||
patch['form.productId'] = ''
|
||
patch.selectedProduct = {}
|
||
patch.selectedProductPriceText = ''
|
||
patch['form.manualProductDescription'] = this.data.unifiedStyleDescription || ''
|
||
Object.assign(patch, buildManualProductImagePatch([]))
|
||
}
|
||
this.setData(patch)
|
||
},
|
||
|
||
onUnifiedStyleDescriptionInput(event) {
|
||
const description = event.detail.value || ''
|
||
const patch = {
|
||
unifiedStyleDescription: description,
|
||
'form.remark': description
|
||
}
|
||
if (!this.data.form.productId) {
|
||
patch['form.manualProductDescription'] = description
|
||
}
|
||
this.setData(patch)
|
||
},
|
||
|
||
onCustomerInput(event) {
|
||
const field = event.currentTarget.dataset.field
|
||
const patch = {
|
||
[`form.${field}`]: event.detail.value,
|
||
'form.customerUserId': '',
|
||
'form.createCustomerRecord': false
|
||
}
|
||
this.setData({
|
||
...patch
|
||
})
|
||
const customerName = field === 'customerName' ? event.detail.value : this.data.form.customerName
|
||
const phone = field === 'phone' ? event.detail.value : this.data.form.phone
|
||
this.refreshCustomerSuggestions(customerName, phone)
|
||
},
|
||
|
||
refreshCustomerSuggestions(nameValue, phoneValue) {
|
||
const name = String(nameValue || '').trim().toLowerCase()
|
||
const phone = String(phoneValue || '').trim().toLowerCase()
|
||
if (!name && !phone) {
|
||
this._customerSuggestionSeq = (this._customerSuggestionSeq || 0) + 1
|
||
clearTimeout(this._suggestionTimer)
|
||
this.setData({ customerSuggestions: [] })
|
||
return
|
||
}
|
||
const suggestions = this.data.customerDirectory
|
||
.filter(customer => (!name || customer.name.toLowerCase().includes(name)) && (!phone || customer.phone.toLowerCase().includes(phone)))
|
||
.slice(0, 3)
|
||
.map(buildCustomerSelectorItem)
|
||
this.setData({ customerSuggestions: suggestions })
|
||
const requestSeq = (this._customerSuggestionSeq || 0) + 1
|
||
this._customerSuggestionSeq = requestSeq
|
||
clearTimeout(this._suggestionTimer)
|
||
this._suggestionTimer = setTimeout(async () => {
|
||
try {
|
||
const result = await customersApi.listForAppointment({ page: 1, size: 50, keyword: name || phone })
|
||
if (requestSeq !== this._customerSuggestionSeq) return
|
||
const rows = Array.isArray(result) ? result : (result.list || [])
|
||
const remoteSuggestions = rows.map(normalizeCustomer)
|
||
.filter(customer => !name || customer.name.toLowerCase().includes(name))
|
||
.slice(0, 3)
|
||
.map(buildCustomerSelectorItem)
|
||
this.setData({ customerSuggestions: remoteSuggestions })
|
||
} catch (error) {
|
||
if (requestSeq === this._customerSuggestionSeq && suggestions.length === 0) {
|
||
this.setData({ customerSuggestions: [] })
|
||
}
|
||
}
|
||
}, 240)
|
||
},
|
||
|
||
selectCustomerSuggestion(event) {
|
||
const index = Number(event.currentTarget.dataset.index)
|
||
const customer = this.data.customerSuggestions[index]
|
||
if (!customer) return
|
||
this.setData({
|
||
'form.customerUserId': customer.id,
|
||
'form.customerName': customer.name,
|
||
// 后端仅返回脱敏号码,不回填到表单,避免把脱敏值当真实号码提交
|
||
'form.phone': '',
|
||
'form.createCustomerRecord': false,
|
||
customerSuggestions: [],
|
||
customerSheetVisible: false,
|
||
customerKeyword: ''
|
||
})
|
||
},
|
||
|
||
openCustomerSheet() {
|
||
this.setData({ customerSheetVisible: true })
|
||
this.searchCustomers(this.data.customerKeyword)
|
||
},
|
||
|
||
closeCustomerSheet() {
|
||
this.setData({ customerSheetVisible: false })
|
||
},
|
||
|
||
onCustomerSearch(event) {
|
||
const keyword = event.detail.value
|
||
this.setData({ customerKeyword: keyword })
|
||
clearTimeout(this._customerTimer)
|
||
this._customerTimer = setTimeout(() => this.searchCustomers(keyword), 250)
|
||
},
|
||
|
||
async searchCustomers(keywordValue) {
|
||
if (!this.data.canCreateAppointment) {
|
||
return
|
||
}
|
||
const keyword = String(keywordValue === undefined ? this.data.customerKeyword : keywordValue || '').trim()
|
||
if (keyword) {
|
||
// 号码已全场景脱敏,按手机号检索必须交给后端精确匹配
|
||
try {
|
||
const result = await customersApi.listForAppointment({ page: 1, size: 100, keyword })
|
||
const rows = Array.isArray(result) ? result : (result.list || [])
|
||
this.setData({
|
||
customerOptions: this.sortCustomerOptions(rows.map(normalizeCustomer)),
|
||
customerError: ''
|
||
})
|
||
} catch (error) {
|
||
this.setData({ customerOptions: [], customerError: toUserMessage(error, '客户加载失败') })
|
||
}
|
||
return
|
||
}
|
||
if (this.data.customerDirectory.length === 0) await this.loadCustomerDirectory()
|
||
this.setData({
|
||
customerOptions: this.sortCustomerOptions(this.data.customerDirectory),
|
||
customerError: ''
|
||
})
|
||
},
|
||
|
||
changeCustomerView(event) {
|
||
this.setData({ customerViewMode: event.detail.mode || 'list' })
|
||
},
|
||
|
||
toggleCustomerSort() {
|
||
const customerNewestFirst = !this.data.customerNewestFirst
|
||
this.setData({
|
||
customerNewestFirst,
|
||
customerOptions: this.sortCustomerOptions(this.data.customerOptions, customerNewestFirst)
|
||
})
|
||
},
|
||
|
||
retryCustomerSearch() {
|
||
this.searchCustomers(this.data.customerKeyword)
|
||
},
|
||
|
||
selectCustomer(event) {
|
||
const customer = event.detail.item
|
||
if (!customer) {
|
||
return
|
||
}
|
||
this.setData({
|
||
'form.customerUserId': customer.id,
|
||
'form.customerName': customer.name,
|
||
// 选择已有客户时不回填脱敏号码,手机号仅在用户主动修改时提交
|
||
'form.phone': '',
|
||
'form.createCustomerRecord': false,
|
||
customerSheetVisible: false,
|
||
customerKeyword: '',
|
||
customerSuggestions: []
|
||
})
|
||
},
|
||
|
||
onUnload() {
|
||
this.flushDraftSave()
|
||
if (this._customerTimer) {
|
||
clearTimeout(this._customerTimer)
|
||
}
|
||
if (this._suggestionTimer) {
|
||
clearTimeout(this._suggestionTimer)
|
||
}
|
||
},
|
||
|
||
installDraftAutoSave() {
|
||
if (this._draftSetDataInstalled) return
|
||
const setData = this.setData.bind(this)
|
||
this.setData = (patch, callback) => {
|
||
const formChanged = patch && Object.keys(patch).some(key => key === 'form' || key.startsWith('form.'))
|
||
const result = setData(patch, callback)
|
||
if (formChanged) this.scheduleDraftSave()
|
||
return result
|
||
}
|
||
this._draftSetDataInstalled = true
|
||
},
|
||
|
||
scheduleDraftSave() {
|
||
if (!this._draftReady || this._draftPersistenceDisabled) return
|
||
if (this._draftTimer) clearTimeout(this._draftTimer)
|
||
this._draftTimer = setTimeout(() => {
|
||
this._draftTimer = null
|
||
this.persistDraft(false)
|
||
}, DRAFT_SAVE_DELAY_MS)
|
||
},
|
||
|
||
cancelDraftSave() {
|
||
if (this._draftTimer) clearTimeout(this._draftTimer)
|
||
this._draftTimer = null
|
||
},
|
||
|
||
flushDraftSave() {
|
||
if (!this._draftTimer) return
|
||
this.cancelDraftSave()
|
||
this.persistDraft(false)
|
||
},
|
||
|
||
persistDraft(showToast) {
|
||
try {
|
||
if (!hasDraftContent(
|
||
this.data.form,
|
||
this._entryDefaults || {},
|
||
this.data.selectedArtist,
|
||
this.data.defaultAppointmentDurationMinutes
|
||
)) {
|
||
removeDraftForm()
|
||
this.setData({ draftSavedAtText: '内容变更后自动保存到本机,保留7天' })
|
||
if (showToast) wx.showToast({ title: '当前没有需要保存的内容', icon: 'none' })
|
||
return false
|
||
}
|
||
const savedAt = writeDraftForm(
|
||
this.data.form,
|
||
this.data.selectedArtist && this.data.selectedArtist.id,
|
||
this.data.durationManuallyChanged
|
||
)
|
||
this.setData({ draftSavedAtText: formatDraftStatus(showToast ? '草稿已手动保存' : '草稿已自动保存', savedAt) })
|
||
if (showToast) wx.showToast({ title: '草稿已保存', icon: 'success' })
|
||
return true
|
||
} catch (error) {
|
||
this.setData({ draftSavedAtText: '草稿保存失败,请点击保存草稿重试' })
|
||
if (showToast) showErrorToast(error, '草稿保存失败')
|
||
return false
|
||
}
|
||
},
|
||
|
||
async resetForm() {
|
||
if (this.data.loading) {
|
||
wx.showToast({ title: '预约正在提交,请稍后再恢复默认值', icon: 'none' })
|
||
return
|
||
}
|
||
if (this.data.manualImageUploading) {
|
||
wx.showToast({ title: '图片上传中,请稍后再恢复默认值', icon: 'none' })
|
||
return
|
||
}
|
||
const result = await showActionModal(this, {
|
||
title: '恢复默认值',
|
||
content: '将清除本表单内容和本机草稿,但不会删除已上传图片文件。保留日历带入的日期和美甲师,确定继续吗?',
|
||
cancelText: '继续填写',
|
||
confirmText: '恢复默认',
|
||
confirmType: 'danger'
|
||
})
|
||
if (!result.confirm) return
|
||
this.cancelDraftSave()
|
||
try {
|
||
removeDraftForm()
|
||
} catch (error) {
|
||
showErrorToast(error, '草稿清理失败,请稍后重试')
|
||
return
|
||
}
|
||
const defaults = this._entryDefaults || {}
|
||
const appointmentDate = defaults.appointmentDate || ''
|
||
const artistId = defaults.artistId || ''
|
||
const artistSelectionId = defaults.artistSelectionId || artistId
|
||
const durationMinutes = String(this.data.defaultAppointmentDurationMinutes || 60)
|
||
const selectedArtist = artistSelectionId === '__unassigned__'
|
||
? { id: '__unassigned__', name: '暂不分配美甲师' }
|
||
: artistId ? findArtist(this.data.artists, artistId) : {}
|
||
const dateLabels = buildAppointmentDateLabels(appointmentDate)
|
||
this._draftPersistenceDisabled = true
|
||
this.setData({
|
||
form: {
|
||
...this.data.form,
|
||
customerUserId: '',
|
||
customerName: '',
|
||
phone: '',
|
||
wechatId: '',
|
||
appointmentDate,
|
||
appointmentTime: '',
|
||
amount: '',
|
||
productId: '',
|
||
manualProductTitle: '',
|
||
manualProductPrice: '',
|
||
manualProductDescription: '',
|
||
manualProductTags: '',
|
||
manualProductTargetAudience: '',
|
||
manualProductPrecautions: '',
|
||
manualProductImageFileIds: '',
|
||
manualProductImageUrl: '',
|
||
manualProductImages: [],
|
||
durationMinutes,
|
||
artistId: artistSelectionId === '__unassigned__' ? '' : artistId,
|
||
createCustomerRecord: false,
|
||
remark: ''
|
||
},
|
||
selectedProduct: {},
|
||
selectedProductPriceText: '',
|
||
selectedArtist,
|
||
customerSuggestions: [],
|
||
customerKeyword: '',
|
||
durationManuallyChanged: false,
|
||
manualProductTitleLength: 0,
|
||
unifiedStyleDescription: '',
|
||
draftSavedAtText: '已恢复默认值;后续修改会自动保存到本机',
|
||
appointmentDayLabel: dateLabels.day,
|
||
appointmentDateBadge: dateLabels.badge,
|
||
appointmentDateLong: dateLabels.long,
|
||
conflictTip: '',
|
||
conflictLevel: 'free',
|
||
timeError: '',
|
||
selectedTimeCandidate: '',
|
||
timeSheetVisible: false,
|
||
timePickerMode: 'wheel',
|
||
manualProductSheetVisible: false,
|
||
manualProductMoreVisible: false,
|
||
productModalVisible: false,
|
||
customerSheetVisible: false,
|
||
artistSheetVisible: false
|
||
})
|
||
this._draftPersistenceDisabled = false
|
||
await this.refreshAvailableTimes()
|
||
},
|
||
|
||
async onDateChange(event) {
|
||
const nextDate = event.detail.value
|
||
const today = dateUtil.formatDate(new Date())
|
||
if (nextDate < today) {
|
||
const result = await showActionModal(this, {
|
||
title: '历史日期不能新建预约',
|
||
content: '之前的日期只能作为历史补单记录,不会校验美甲师排班,也不会占用预约时段。',
|
||
cancelText: '取消',
|
||
confirmText: '去补单'
|
||
})
|
||
if (result.confirm) {
|
||
const query = [`serviceDate=${encodeURIComponent(nextDate)}`]
|
||
if (this.data.form.artistId) {
|
||
query.push(`artistId=${encodeURIComponent(this.data.form.artistId)}`)
|
||
}
|
||
wx.navigateTo({ url: `/pages/backfill-order/index?${query.join('&')}` })
|
||
}
|
||
return
|
||
}
|
||
const dateLabels = buildAppointmentDateLabels(nextDate)
|
||
this.setData({
|
||
'form.appointmentDate': nextDate,
|
||
'form.appointmentTime': '',
|
||
appointmentDayLabel: dateLabels.day,
|
||
appointmentDateBadge: dateLabels.badge,
|
||
appointmentDateLong: dateLabels.long
|
||
})
|
||
await this.loadArtists()
|
||
await this.refreshAvailableTimes()
|
||
this.checkAvailability()
|
||
},
|
||
|
||
refreshProductCards() {
|
||
const keyword = this.data.productKeyword.trim().toLowerCase()
|
||
const products = this.data.products
|
||
.map(product => normalizeProduct(product, this.data.artists))
|
||
.filter(product => {
|
||
if (!keyword) return true
|
||
return [product.title, product.artistText, product.priceText, product.durationText, ...(product.tagList || [])]
|
||
.some(value => String(value || '').toLowerCase().includes(keyword))
|
||
})
|
||
this.setData({ filteredProducts: products })
|
||
},
|
||
|
||
openProductModal() {
|
||
this.refreshProductCards()
|
||
this.setData({ productModalVisible: true, manualProductSheetVisible: false })
|
||
},
|
||
|
||
closeProductModal() {
|
||
this.setData({ productModalVisible: false })
|
||
},
|
||
|
||
openManualProduct() {
|
||
this.setData({
|
||
productModalVisible: false,
|
||
manualProductSheetVisible: true,
|
||
manualProductMoreVisible: false,
|
||
unifiedStyleDescription: this.data.form.remark || this.data.form.manualProductDescription || this.data.unifiedStyleDescription || '',
|
||
manualProductTitleLength: this.data.form.productId
|
||
? String(this.data.selectedProduct.title || '').length
|
||
: String(this.data.form.manualProductTitle || '').length
|
||
})
|
||
},
|
||
|
||
openManualProductFromLibrary() {
|
||
const patch = {
|
||
'form.productId': '',
|
||
selectedProduct: {},
|
||
selectedProductPriceText: '',
|
||
unifiedStyleDescription: this.data.form.remark || this.data.form.manualProductDescription || this.data.unifiedStyleDescription || '',
|
||
manualProductTitleLength: String(this.data.form.manualProductTitle || '').length,
|
||
productModalVisible: false,
|
||
manualProductSheetVisible: true,
|
||
manualProductMoreVisible: false
|
||
}
|
||
if (this.data.form.productId) {
|
||
patch['form.manualProductTitle'] = ''
|
||
patch['form.manualProductDescription'] = this.data.unifiedStyleDescription || ''
|
||
patch.manualProductTitleLength = 0
|
||
}
|
||
this.setData(patch)
|
||
},
|
||
|
||
closeManualProduct() {
|
||
this.setData({ manualProductSheetVisible: false })
|
||
},
|
||
|
||
toggleManualProductMore() {
|
||
this.setData({ manualProductMoreVisible: !this.data.manualProductMoreVisible })
|
||
},
|
||
|
||
confirmManualProduct() {
|
||
if (!this.data.form.productId) {
|
||
const hasTitle = Boolean(String(this.data.form.manualProductTitle || '').trim())
|
||
const hasImage = (this.data.form.manualProductImages || []).length > 0 || Boolean(String(this.data.form.manualProductImageFileIds || '').trim())
|
||
const hasFallbackName = Boolean(String(this.data.form.customerName || '').trim())
|
||
if (!hasTitle && !hasImage && !hasFallbackName) {
|
||
wx.showToast({ title: '请填写款式名称或添加图片', icon: 'none' })
|
||
return
|
||
}
|
||
}
|
||
const amountText = String(this.data.form.amount === undefined || this.data.form.amount === null ? '' : this.data.form.amount).trim()
|
||
const amount = Number(amountText)
|
||
if (!amountText || !Number.isFinite(amount) || amount < 0) {
|
||
wx.showToast({ title: '请输入不小于0的预约金额', icon: 'none' })
|
||
return
|
||
}
|
||
if (!normalizeDuration(this.data.form.durationMinutes)) {
|
||
wx.showToast({ title: '请输入大于0分钟的预计时长', icon: 'none' })
|
||
return
|
||
}
|
||
if (this.data.form.productId) {
|
||
this.setData({ manualProductSheetVisible: false })
|
||
this.refreshAvailableTimes()
|
||
this.checkAvailability()
|
||
return
|
||
}
|
||
this.setData({ 'form.productId': '', selectedProduct: {}, selectedProductPriceText: '', manualProductSheetVisible: false })
|
||
this.refreshAvailableTimes()
|
||
this.checkAvailability()
|
||
},
|
||
|
||
stopTap() {
|
||
},
|
||
|
||
stopTouchMove() {
|
||
},
|
||
|
||
onProductSearch(event) {
|
||
this.setData({ productKeyword: event.detail.value })
|
||
this.refreshProductCards()
|
||
},
|
||
|
||
selectProduct(event) {
|
||
const selectedProduct = event.detail.item || this.data.filteredProducts.find(item => String(item.id) === String(event.currentTarget.dataset.id)) || {}
|
||
const selectedDuration = parseInt(selectedProduct.serviceDurationMinutes || selectedProduct.approximateDuration, 10)
|
||
this.setData({
|
||
selectedProduct,
|
||
selectedProductPriceText: selectedProduct.priceText || '',
|
||
unifiedStyleDescription: this.data.form.remark || '',
|
||
manualProductTitleLength: String(selectedProduct.title || '').length,
|
||
'form.productId': selectedProduct.id,
|
||
'form.manualProductTitle': '',
|
||
'form.manualProductPrice': '',
|
||
'form.manualProductDescription': '',
|
||
'form.manualProductTags': '',
|
||
'form.manualProductTargetAudience': '',
|
||
'form.manualProductPrecautions': '',
|
||
'form.manualProductImageFileIds': '',
|
||
'form.manualProductImageUrl': '',
|
||
'form.manualProductImages': [],
|
||
'form.amount': selectedProduct.price === undefined || selectedProduct.price === null ? '' : String(selectedProduct.price),
|
||
'form.durationMinutes': String(selectedDuration || this.data.defaultAppointmentDurationMinutes || 60),
|
||
durationManuallyChanged: false
|
||
})
|
||
this.closeProductModal()
|
||
this.refreshAvailableTimes()
|
||
this.checkAvailability()
|
||
},
|
||
|
||
async chooseManualProductImage() {
|
||
if (this.data.manualImageUploading) {
|
||
return
|
||
}
|
||
const remainingCount = 9 - (this.data.form.manualProductImages || []).length
|
||
if (remainingCount <= 0) {
|
||
wx.showToast({ title: '最多添加9张图片', icon: 'none' })
|
||
return
|
||
}
|
||
try {
|
||
this.setData({ manualImageUploading: true })
|
||
const filePaths = await chooseManualProductImagePaths(remainingCount)
|
||
if (!filePaths.length) {
|
||
return
|
||
}
|
||
for (const filePath of filePaths) {
|
||
const uploadResult = await uploadObjectFile(filePath)
|
||
const fileId = uploadResult.id || uploadResult.fileId
|
||
const fileUrl = uploadResult.fileUrl || uploadResult.primaryUrl || ''
|
||
if (!fileId) {
|
||
throw new Error('作品图片上传成功但未返回文件ID')
|
||
}
|
||
const images = (this.data.form.manualProductImages || []).concat({
|
||
fileId: String(fileId),
|
||
fileUrl,
|
||
previewUrl: filePath
|
||
}).slice(0, 9)
|
||
this.setData({
|
||
...buildManualProductImagePatch(images),
|
||
'form.productId': '',
|
||
selectedProduct: {},
|
||
selectedProductPriceText: ''
|
||
})
|
||
}
|
||
if (filePaths.length > 1) {
|
||
wx.showToast({ title: `已添加${filePaths.length}张图片`, icon: 'success' })
|
||
}
|
||
} catch (error) {
|
||
showErrorToast(error, '图片上传失败')
|
||
} finally {
|
||
this.setData({ manualImageUploading: false })
|
||
}
|
||
},
|
||
|
||
onManualProductImageError(event) {
|
||
const index = Number(event && event.currentTarget && event.currentTarget.dataset.index)
|
||
const images = this.data.form.manualProductImages || []
|
||
const image = images[index]
|
||
if (!Number.isInteger(index) || !image || !image.previewUrl || !image.fileUrl || image.previewUrl === image.fileUrl) {
|
||
return
|
||
}
|
||
const fallbackImages = images.slice()
|
||
fallbackImages[index] = { ...image, previewUrl: image.fileUrl }
|
||
this.setData(buildManualProductImagePatch(fallbackImages))
|
||
},
|
||
|
||
removeManualProductImage(event) {
|
||
if (this.data.manualImageUploading) {
|
||
return
|
||
}
|
||
const index = Number(event && event.currentTarget && event.currentTarget.dataset.index)
|
||
const images = this.data.form.manualProductImages || []
|
||
if (!Number.isInteger(index) || index < 0 || index >= images.length) {
|
||
return
|
||
}
|
||
this.setData(buildManualProductImagePatch(images.filter((image, imageIndex) => imageIndex !== index)))
|
||
},
|
||
|
||
filterArtistItems(artists, keywordValue) {
|
||
const keyword = String(keywordValue || '').trim().toLowerCase()
|
||
const items = (artists || [])
|
||
.filter(item => !keyword || String(item.name || '').toLowerCase().includes(keyword))
|
||
.map(buildArtistSelectorItem)
|
||
if (!keyword || '暂不分配'.includes(keyword)) {
|
||
items.unshift({ id: '__unassigned__', title: '暂不分配', subtitle: '先记录预约,后续再分配美甲师', badge: '待分配' })
|
||
}
|
||
return items
|
||
},
|
||
|
||
openArtistSheet() {
|
||
this.setData({
|
||
artistSheetVisible: true,
|
||
artistSelectorItems: this.filterArtistItems(this.data.artists, this.data.artistKeyword)
|
||
})
|
||
},
|
||
|
||
closeArtistSheet() {
|
||
this.setData({ artistSheetVisible: false })
|
||
},
|
||
|
||
retryArtists() {
|
||
this.loadArtists()
|
||
},
|
||
|
||
onArtistSearch(event) {
|
||
const artistKeyword = event.detail.value
|
||
this.setData({
|
||
artistKeyword,
|
||
artistSelectorItems: this.filterArtistItems(this.data.artists, artistKeyword)
|
||
})
|
||
},
|
||
|
||
selectArtist(event) {
|
||
const selectedArtist = event.detail.item || {}
|
||
if (selectedArtist.id === '__unassigned__') {
|
||
this.setData({
|
||
selectedArtist: { id: '__unassigned__', name: '暂不分配美甲师' },
|
||
'form.artistId': '',
|
||
artistSheetVisible: false,
|
||
conflictTip: '',
|
||
conflictLevel: 'free'
|
||
})
|
||
this.refreshAvailableTimes()
|
||
return
|
||
}
|
||
this.setData({
|
||
selectedArtist,
|
||
'form.artistId': selectedArtist.id,
|
||
'form.appointmentTime': '',
|
||
artistSheetVisible: false
|
||
})
|
||
this.refreshAvailableTimes()
|
||
this.checkAvailability()
|
||
},
|
||
|
||
addEmployeeFromSelector() {
|
||
this.setData({ artistSheetVisible: false })
|
||
wx.navigateTo({
|
||
url: `/pages/employee-create/index?picker=1&date=${encodeURIComponent(this.data.form.appointmentDate || '')}&time=${encodeURIComponent(this.data.form.appointmentTime || '')}&durationMinutes=${encodeURIComponent(this.data.form.durationMinutes || '')}`,
|
||
success: result => {
|
||
result.eventChannel.on('employeeCreated', employee => this.handleEmployeeCreated(employee))
|
||
}
|
||
})
|
||
},
|
||
|
||
async handleEmployeeCreated(employee) {
|
||
const originalTime = this.data.form.appointmentTime
|
||
await this.loadArtists(employee.autoSelect === false ? '' : employee.id, employee)
|
||
if (employee.autoSelect === false) {
|
||
this.setData({ selectedArtist: {}, 'form.artistId': '' })
|
||
await this.refreshAvailableTimes()
|
||
return
|
||
}
|
||
if (employee.scheduleSaved && originalTime) {
|
||
const availability = await this.checkAvailability()
|
||
if (!availability.ok) {
|
||
this.setData({
|
||
selectedArtist: {},
|
||
'form.artistId': '',
|
||
'form.appointmentTime': originalTime,
|
||
conflictTip: `${availability.tip || '新美甲师当前排班无法承接'},预约已保持待分配`,
|
||
conflictLevel: 'danger'
|
||
})
|
||
}
|
||
} else {
|
||
this.setData({ 'form.appointmentTime': '' })
|
||
}
|
||
await this.refreshAvailableTimes()
|
||
if (this.data.form.artistId) this.checkAvailability()
|
||
},
|
||
|
||
canOpenTimeSheet() {
|
||
const form = this.data.form
|
||
return Boolean(form.appointmentDate && normalizeDuration(form.durationMinutes))
|
||
},
|
||
|
||
async refreshAvailableTimes() {
|
||
const form = this.data.form
|
||
const durationMinutes = normalizeDuration(form.durationMinutes)
|
||
const requestSeq = (this._availableTimeRequestSeq || 0) + 1
|
||
this._availableTimeRequestSeq = requestSeq
|
||
if (!form.appointmentDate || !durationMinutes) {
|
||
const patch = {
|
||
availableTimeGroups: [],
|
||
timePickerGroups: [],
|
||
timePickerSlots: [],
|
||
timePickerHours: [],
|
||
timePickerMinutes: [],
|
||
timePickerValue: [0, 0],
|
||
selectedTimeCandidate: '',
|
||
timePickerCandidateStatus: 'off-shift',
|
||
timeError: '',
|
||
businessHoursMissing: false,
|
||
timeSelectTip: '请先填写预约日期和时长'
|
||
}
|
||
if (form.appointmentTime) {
|
||
patch['form.appointmentTime'] = ''
|
||
}
|
||
this.setData(patch)
|
||
return
|
||
}
|
||
if (!form.artistId) {
|
||
this.setData({ timeLoading: true, timeError: '', timeSelectTip: '正在加载营业时间...' })
|
||
try {
|
||
const calendar = await planningApi.calendar({ startDate: form.appointmentDate, endDate: form.appointmentDate })
|
||
if (requestSeq !== this._availableTimeRequestSeq) return
|
||
const businessHours = resolveBusinessHours(calendar, form.appointmentDate)
|
||
const businessStartTime = businessHours.start
|
||
const businessEndTime = businessHours.end
|
||
if (!businessStartTime) {
|
||
const closed = businessHours.closed === true
|
||
const message = closed ? '预约日期门店休息,不能新建普通预约' : '门店营业时间尚未设置,请先完成设置'
|
||
this.setData({
|
||
businessStartTime: '',
|
||
businessEndTime: '',
|
||
availableTimeGroups: [],
|
||
timePickerSlots: [],
|
||
timePickerGroups: [],
|
||
timePickerHours: [],
|
||
timePickerMinutes: [],
|
||
selectedTimeCandidate: '',
|
||
'form.appointmentTime': '',
|
||
timeError: message,
|
||
businessHoursMissing: !closed,
|
||
timeLoading: false,
|
||
timeSelectTip: closed ? '门店休息日不可预约' : '请先设置门店营业时间'
|
||
})
|
||
return
|
||
}
|
||
this.setData({ businessStartTime, businessEndTime })
|
||
const availableTimeGroups = buildUnassignedTimeGroups(durationMinutes, businessStartTime, businessEndTime, form.appointmentDate)
|
||
const timePickerSlots = buildTimePickerSlots(calendar, form, durationMinutes)
|
||
this.setData({
|
||
availableTimeGroups,
|
||
timePickerSlots,
|
||
timePickerGroups: buildTimePickerGroups(timePickerSlots),
|
||
...buildTimeWheelState(timePickerSlots, form.appointmentTime),
|
||
timeError: '',
|
||
businessHoursMissing: false,
|
||
timeLoading: false,
|
||
timeSelectTip: availableTimeGroups.length ? '请选择预约时间,美甲师可稍后分配' : '当前日期没有可选时段'
|
||
})
|
||
} catch (error) {
|
||
if (requestSeq === this._availableTimeRequestSeq) {
|
||
this.setData({
|
||
businessStartTime: '',
|
||
businessEndTime: '',
|
||
availableTimeGroups: [],
|
||
timePickerSlots: [],
|
||
timePickerGroups: [],
|
||
timePickerHours: [],
|
||
timePickerMinutes: [],
|
||
selectedTimeCandidate: '',
|
||
'form.appointmentTime': '',
|
||
timeError: toUserMessage(error, '营业时间加载失败'),
|
||
businessHoursMissing: false,
|
||
timeLoading: false,
|
||
timeSelectTip: '营业时间加载失败'
|
||
})
|
||
}
|
||
}
|
||
return
|
||
}
|
||
this.setData({
|
||
timeLoading: true,
|
||
timeError: '',
|
||
businessHoursMissing: false,
|
||
timeSelectTip: '正在计算可约时间...'
|
||
})
|
||
try {
|
||
const calendar = await planningApi.calendar({
|
||
startDate: form.appointmentDate,
|
||
endDate: form.appointmentDate,
|
||
artistId: form.artistId
|
||
})
|
||
if (requestSeq !== this._availableTimeRequestSeq) {
|
||
return
|
||
}
|
||
const businessHours = resolveBusinessHours(calendar, form.appointmentDate)
|
||
if (!businessHours.start) {
|
||
const closed = businessHours.closed === true
|
||
const message = closed ? '预约日期门店休息,不能新建普通预约' : '门店营业时间尚未设置,请先完成设置'
|
||
this.setData({
|
||
businessStartTime: '',
|
||
businessEndTime: '',
|
||
availableTimeGroups: [],
|
||
timePickerSlots: [],
|
||
timePickerGroups: [],
|
||
timePickerHours: [],
|
||
timePickerMinutes: [],
|
||
selectedTimeCandidate: '',
|
||
'form.appointmentTime': '',
|
||
timeError: message,
|
||
businessHoursMissing: !closed,
|
||
timeLoading: false,
|
||
timeSelectTip: closed ? '门店休息日不可预约' : '请先设置门店营业时间'
|
||
})
|
||
return
|
||
}
|
||
const availableTimeGroups = buildAvailableTimeGroups(calendar, form, durationMinutes)
|
||
const availableTimes = flattenTimeGroups(availableTimeGroups).map(item => item.value)
|
||
const timePickerSlots = buildTimePickerSlots(calendar, form, durationMinutes)
|
||
const patch = {
|
||
availableTimeGroups,
|
||
timePickerSlots,
|
||
timePickerGroups: buildTimePickerGroups(timePickerSlots),
|
||
...buildTimeWheelState(timePickerSlots, form.appointmentTime),
|
||
timeError: '',
|
||
businessHoursMissing: false,
|
||
timeSelectTip: availableTimes.length > 0 ? '请选择预约时间' : '当前美甲师当天暂无可约时间'
|
||
}
|
||
if (form.appointmentTime && !availableTimes.includes(form.appointmentTime)) {
|
||
patch['form.appointmentTime'] = ''
|
||
}
|
||
this.setData(patch)
|
||
} catch (error) {
|
||
if (requestSeq !== this._availableTimeRequestSeq) {
|
||
return
|
||
}
|
||
this.setData({
|
||
businessStartTime: '',
|
||
businessEndTime: '',
|
||
availableTimeGroups: [],
|
||
timePickerSlots: [],
|
||
timePickerGroups: [],
|
||
timePickerHours: [],
|
||
timePickerMinutes: [],
|
||
selectedTimeCandidate: '',
|
||
'form.appointmentTime': '',
|
||
timeError: toUserMessage(error, '可约时间加载失败'),
|
||
businessHoursMissing: false,
|
||
timeSelectTip: '可约时间加载失败'
|
||
})
|
||
} finally {
|
||
if (requestSeq === this._availableTimeRequestSeq) {
|
||
this.setData({ timeLoading: false })
|
||
}
|
||
}
|
||
},
|
||
|
||
async openTimeSheet() {
|
||
if (!this.canOpenTimeSheet()) {
|
||
wx.showToast({ title: '请先填写预约日期和时长', icon: 'none' })
|
||
return
|
||
}
|
||
this.setData({ timeSheetVisible: true, timePickerMode: 'wheel' })
|
||
await this.refreshAvailableTimes()
|
||
},
|
||
|
||
closeTimeSheet() {
|
||
this.setData({ timeSheetVisible: false })
|
||
},
|
||
|
||
selectAvailableTime(event) {
|
||
const value = event.currentTarget.dataset.value
|
||
const slot = this.data.timePickerSlots.find(item => item.value === value)
|
||
if (!slot || slot.status !== 'available') {
|
||
if (slot && slot.status === 'past') {
|
||
this.showBackfillPrompt(this.data.form.appointmentDate, '所选时段已经过去')
|
||
return
|
||
}
|
||
wx.showToast({ title: slot && slot.status === 'occupied' ? '该时间已被占用' : '该时间不可预约', icon: 'none' })
|
||
return
|
||
}
|
||
this.setData({ selectedTimeCandidate: value, timePickerCandidateStatus: slot.status })
|
||
},
|
||
|
||
onTimePickerModeChange(event) {
|
||
this.setData({ timePickerMode: event.currentTarget.dataset.mode || 'wheel' })
|
||
},
|
||
|
||
onTimePickerChange(event) {
|
||
const values = event.detail.value || [0, 0]
|
||
const hourItem = this.data.timePickerHours[values[0]]
|
||
if (!hourItem) return
|
||
const hour = Number(hourItem.value)
|
||
const minuteIndex = Number(values[1] || 0)
|
||
const minuteItem = this.data.timePickerMinutes[minuteIndex]
|
||
const minute = minuteItem ? Number(minuteItem.value) : 0
|
||
const candidate = `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`
|
||
const slot = this.data.timePickerSlots.find(item => item.value === candidate)
|
||
const nextMinutes = timeWheelStateForHour(this.data.timePickerSlots, hour, minute)
|
||
this.setData({
|
||
timePickerValue: [Number(values[0]), nextMinutes.selectedMinuteIndex],
|
||
timePickerMinutes: nextMinutes.timePickerMinutes,
|
||
selectedTimeCandidate: candidate,
|
||
timePickerCandidateStatus: slot ? slot.status : 'off-shift'
|
||
})
|
||
},
|
||
|
||
confirmTimeSelection() {
|
||
const candidate = this.data.selectedTimeCandidate
|
||
const slot = this.data.timePickerSlots.find(item => item.value === candidate)
|
||
if (!slot || slot.status !== 'available') {
|
||
if (slot && slot.status === 'past') {
|
||
this.showBackfillPrompt(this.data.form.appointmentDate, '所选时段已经过去')
|
||
return
|
||
}
|
||
wx.showToast({ title: slot && slot.status === 'occupied' ? '该时间已被占用' : '该时间不可预约', icon: 'none' })
|
||
return
|
||
}
|
||
this.checkAvailability(candidate).then(availability => {
|
||
if (!availability.ok) {
|
||
wx.showToast({
|
||
title: availability.tip && availability.tip.includes('已有预约') ? '该时间已被占用' : availability.tip || '该时间不可预约',
|
||
icon: 'none'
|
||
})
|
||
return
|
||
}
|
||
this.setData({ 'form.appointmentTime': candidate, timeSheetVisible: false })
|
||
this.checkAvailability()
|
||
})
|
||
},
|
||
|
||
async showBackfillPrompt(serviceDate, reason = '该日期或时段已过去') {
|
||
const result = await showActionModal(this, {
|
||
title: '转为历史补单',
|
||
content: `${reason},普通预约不能使用过去时间。可以前往补录历史订单,或取消继续选择未来时间。`,
|
||
cancelText: '取消',
|
||
confirmText: '去补录'
|
||
})
|
||
if (!result.confirm) return
|
||
const query = [`serviceDate=${encodeURIComponent(serviceDate || dateUtil.formatDate(new Date()))}`]
|
||
const artistId = this.data.form.artistId || this._pendingHistoricalArtistId
|
||
if (artistId) query.push(`artistId=${encodeURIComponent(artistId)}`)
|
||
wx.navigateTo({ url: `/pages/backfill-order/index?${query.join('&')}` })
|
||
},
|
||
|
||
async checkAvailability(candidateTime) {
|
||
const form = this.data.form
|
||
const appointmentTime = candidateTime || form.appointmentTime
|
||
if (!form.appointmentDate || !appointmentTime) {
|
||
this.setData({ conflictTip: '', conflictLevel: 'free' })
|
||
return { ok: true }
|
||
}
|
||
const durationMinutes = normalizeDuration(form.durationMinutes)
|
||
if (!durationMinutes) {
|
||
this.setData({ conflictTip: '', conflictLevel: 'free' })
|
||
return { ok: true }
|
||
}
|
||
const startMinute = dateUtil.minutesOfDay(appointmentTime)
|
||
const endMinute = startMinute + durationMinutes
|
||
if (!this.data.businessStartTime || !this.data.businessEndTime) {
|
||
const tip = this.data.businessHoursMissing
|
||
? '门店营业时间尚未设置,请先完成设置'
|
||
: '营业时间暂不可用,请稍后重试'
|
||
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
|
||
return { ok: false, tip }
|
||
}
|
||
if (startMinute < dateUtil.minutesOfDay(this.data.businessStartTime) || endMinute > dateUtil.minutesOfDay(this.data.businessEndTime)) {
|
||
const tip = `该时间超出营业时间 ${this.data.businessStartTime}-${this.data.businessEndTime}`
|
||
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
|
||
return { ok: false, tip }
|
||
}
|
||
const now = new Date()
|
||
const today = dateUtil.formatDate(now)
|
||
if (form.appointmentDate < today || (form.appointmentDate === today && startMinute <= now.getHours() * 60 + now.getMinutes())) {
|
||
const tip = '该时间已过,请改选未来时段或使用历史补单'
|
||
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
|
||
return { ok: false, tip }
|
||
}
|
||
if (!form.artistId) {
|
||
const tip = '预约将保存为待分配,当前不会占用美甲师时间'
|
||
this.setData({ conflictTip: tip, conflictLevel: 'free' })
|
||
return { ok: true, tip }
|
||
}
|
||
try {
|
||
const calendar = await planningApi.calendar({
|
||
startDate: form.appointmentDate,
|
||
endDate: form.appointmentDate,
|
||
artistId: form.artistId
|
||
})
|
||
const schedule = (calendar.schedules || []).find(item => isScheduleCoveringTime(item, form, startMinute, endMinute))
|
||
if (!schedule) {
|
||
const tip = `${this.data.selectedArtist.name || '该美甲师'} 当前时段无可预约排班`
|
||
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
|
||
return { ok: false, tip }
|
||
}
|
||
const conflicts = (calendar.appointments || []).filter(item => {
|
||
if (String(item.artistId) !== String(form.artistId) || normalizeAppointmentDate(item) !== form.appointmentDate) return false
|
||
if (isCancelledAppointment(item)) return false
|
||
const itemStart = resolveAppointmentStartMinute(item)
|
||
const itemEnd = resolveAppointmentEndMinute(item, itemStart)
|
||
return startMinute < itemEnd && endMinute > itemStart
|
||
})
|
||
if (conflicts.length > 0) {
|
||
const first = conflicts[0]
|
||
const itemStart = resolveAppointmentStartMinute(first)
|
||
const itemEnd = resolveAppointmentEndMinute(first, itemStart)
|
||
const tip = `${this.data.selectedArtist.name || '该美甲师'} ${dateUtil.timeFromMinutes(itemStart)}-${dateUtil.timeFromMinutes(itemEnd)} 已有预约`
|
||
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
|
||
return { ok: false, tip }
|
||
}
|
||
const tip = `${this.data.selectedArtist.name || '该美甲师'} ${appointmentTime}-${dateUtil.timeFromMinutes(endMinute)} 可预约`
|
||
this.setData({ conflictTip: tip, conflictLevel: 'free' })
|
||
return { ok: true, tip }
|
||
} catch (error) {
|
||
const tip = toUserMessage(error, '排班校验失败,请稍后重试')
|
||
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
|
||
return { ok: false, tip }
|
||
}
|
||
},
|
||
|
||
async ensureCustomerBeforeSubmit() {
|
||
const name = String(this.data.form.customerName || '').trim()
|
||
const phone = String(this.data.form.phone || '').trim()
|
||
const wechatId = String(this.data.form.wechatId || '').trim()
|
||
if (!name && (phone || wechatId)) {
|
||
this.setData({ 'form.createCustomerRecord': false })
|
||
wx.showToast({ title: '填写联系方式时请同时填写客户姓名', icon: 'none' })
|
||
return false
|
||
}
|
||
if (!name) {
|
||
this.setData({ 'form.createCustomerRecord': false })
|
||
return true
|
||
}
|
||
if (!name) {
|
||
wx.showToast({ title: '填写手机号时请同时填写客户姓名', icon: 'none' })
|
||
return false
|
||
}
|
||
if (phone && !/^1[3-9]\d{9}$/.test(phone)) {
|
||
wx.showToast({ title: '请输入正确手机号', icon: 'none' })
|
||
return false
|
||
}
|
||
if (this.data.form.customerUserId) {
|
||
this.setData({ 'form.createCustomerRecord': false })
|
||
return true
|
||
}
|
||
|
||
this.setData({ loading: true })
|
||
try {
|
||
const matches = await customersApi.matchIdentityForAppointment(name, wechatId || undefined, phone || undefined)
|
||
if (matches.length > 1) {
|
||
const choice = await showActionModal(this, {
|
||
title: '找到多个同名客户',
|
||
content: phone ? '无法确定唯一客户,请选择已有客户或按散客继续。' : '请先补充手机号或选择一个已有客户,也可以按散客继续。',
|
||
cancelText: '不关联提交',
|
||
confirmText: '选择客户'
|
||
})
|
||
if (!choice.confirm) {
|
||
this.setData({ 'form.createCustomerRecord': false })
|
||
return true
|
||
}
|
||
this.setData({
|
||
customerOptions: matches.map(normalizeCustomer).map(buildCustomerSelectorItem),
|
||
customerKeyword: name,
|
||
customerSheetVisible: true
|
||
})
|
||
return false
|
||
}
|
||
if (matches.length > 0) {
|
||
const customer = normalizeCustomer(matches[0])
|
||
const choice = await showActionModal(this, {
|
||
title: '客户已存在',
|
||
content: `系统中已有“${name}”${phone ? `(${phone})` : ''},是否使用该客户?`,
|
||
cancelText: '不关联提交',
|
||
confirmText: '使用已有'
|
||
})
|
||
if (choice.confirm) {
|
||
this.setData({
|
||
'form.customerUserId': customer.id,
|
||
'form.customerName': customer.name,
|
||
'form.createCustomerRecord': false
|
||
})
|
||
} else {
|
||
this.setData({ 'form.createCustomerRecord': false })
|
||
}
|
||
return true
|
||
}
|
||
|
||
const createChoice = await showActionModal(this, {
|
||
title: '新建客户',
|
||
content: '系统中没有匹配客户,是否新建到客户档案?',
|
||
cancelText: '不新建',
|
||
confirmText: '确认'
|
||
})
|
||
this.setData({ 'form.createCustomerRecord': Boolean(createChoice.confirm) })
|
||
return true
|
||
} catch (error) {
|
||
showErrorToast(error, '客户校验失败,请稍后重试')
|
||
return false
|
||
} finally {
|
||
this.setData({ loading: false })
|
||
}
|
||
},
|
||
|
||
async submit() {
|
||
if (this.data.loading) {
|
||
return
|
||
}
|
||
if (!this.data.canCreateAppointment) {
|
||
wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' })
|
||
return
|
||
}
|
||
if (isShopBusinessExpired()) {
|
||
await showBusinessExpiryNotice(this)
|
||
return
|
||
}
|
||
let form = this.data.form
|
||
const today = dateUtil.formatDate(new Date())
|
||
const now = new Date()
|
||
const selectedMinute = form.appointmentTime ? dateUtil.minutesOfDay(form.appointmentTime) : -1
|
||
if (form.appointmentDate < today || (form.appointmentDate === today && selectedMinute <= now.getHours() * 60 + now.getMinutes())) {
|
||
await this.showBackfillPrompt(form.appointmentDate, form.appointmentDate < today ? '所选日期已经过去' : '所选时段已经过去')
|
||
return
|
||
}
|
||
const manualProductTitle = String(form.manualProductTitle || '').trim()
|
||
const manualProductImageFileIds = String(form.manualProductImageFileIds || '').trim()
|
||
const hasManualProduct = Boolean(manualProductTitle || manualProductImageFileIds || String(form.customerName || '').trim())
|
||
const amountText = String(form.amount === undefined || form.amount === null ? '' : form.amount).trim()
|
||
const amount = Number(amountText)
|
||
const durationMinutes = normalizeDuration(form.durationMinutes)
|
||
if ((!form.productId && !hasManualProduct) || !form.appointmentDate || !form.appointmentTime || !amountText) {
|
||
wx.showToast({ title: '请补全预约信息', icon: 'none' })
|
||
return
|
||
}
|
||
if (!Number.isFinite(amount) || amount < 0) {
|
||
wx.showToast({ title: '请输入不小于0的成交金额', icon: 'none' })
|
||
return
|
||
}
|
||
if (form.phone && !String(form.customerName || '').trim()) {
|
||
wx.showToast({ title: '填写手机号时请同时填写客户姓名', icon: 'none' })
|
||
return
|
||
}
|
||
if (form.phone && !/^1[3-9]\d{9}$/.test(String(form.phone).trim())) {
|
||
wx.showToast({ title: '请输入正确手机号', icon: 'none' })
|
||
return
|
||
}
|
||
if (!durationMinutes) {
|
||
wx.showToast({ title: '请填写预约时长', icon: 'none' })
|
||
return
|
||
}
|
||
const availability = await this.checkAvailability()
|
||
if (!availability.ok) {
|
||
wx.showToast({ title: availability.tip || '该时段已被预约', icon: 'none' })
|
||
return
|
||
}
|
||
if (!form.artistId) {
|
||
const result = await showActionModal(this, {
|
||
title: '保存为待分配预约',
|
||
content: '当前未指定美甲师,预约会正常保存,但不会占用美甲师时间。可以稍后在预约详情中分配。',
|
||
cancelText: '返回选择',
|
||
confirmText: '继续保存'
|
||
})
|
||
if (!result.confirm) return
|
||
}
|
||
if (!(await this.ensureCustomerBeforeSubmit())) {
|
||
return
|
||
}
|
||
form = this.data.form
|
||
this.setData({ loading: true })
|
||
try {
|
||
const payload = {
|
||
...form,
|
||
customerUserId: form.customerUserId ? String(form.customerUserId) : undefined,
|
||
artistId: form.artistId ? String(form.artistId) : undefined,
|
||
customerName: String(form.customerName || '').trim() || undefined,
|
||
wechatId: String(form.wechatId || '').trim() || undefined,
|
||
phone: String(form.phone || '').trim() || undefined,
|
||
amount,
|
||
createCustomerRecord: Boolean(form.createCustomerRecord),
|
||
durationMinutes,
|
||
clientRequestId: buildClientRequestId('manager-appointment')
|
||
}
|
||
if (form.productId) {
|
||
payload.productId = String(form.productId)
|
||
payload.manualProductTitle = undefined
|
||
payload.manualProductPrice = undefined
|
||
} else {
|
||
payload.productId = undefined
|
||
payload.manualProductTitle = manualProductTitle || undefined
|
||
payload.manualProductPrice = amount
|
||
payload.manualProductDescription = String(form.manualProductDescription || '').trim() || undefined
|
||
payload.manualProductTags = String(form.manualProductTags || '').trim() || undefined
|
||
payload.manualProductTargetAudience = String(form.manualProductTargetAudience || '').trim() || undefined
|
||
payload.manualProductPrecautions = String(form.manualProductPrecautions || '').trim() || undefined
|
||
payload.manualProductImageFileIds = String(form.manualProductImageFileIds || '').trim() || undefined
|
||
}
|
||
const result = await planningApi.createAppointment(payload)
|
||
this.cancelDraftSave()
|
||
this._draftReady = false
|
||
this._draftPersistenceDisabled = true
|
||
try {
|
||
removeDraftForm()
|
||
} catch (error) {
|
||
console.warn('预约已创建,但草稿清理失败', error)
|
||
}
|
||
markPlanningRefresh()
|
||
wx.redirectTo({ url: `/pages/appointment-detail/index?id=${result.orderItemId}` })
|
||
} catch (error) {
|
||
if ((error.message || '').includes('有效期') || (error.message || '').includes('到期')) {
|
||
await showBusinessExpiryNotice(this)
|
||
} else {
|
||
showErrorToast(error, '提交失败')
|
||
}
|
||
} finally {
|
||
this.setData({ loading: false })
|
||
}
|
||
},
|
||
|
||
saveDraft() {
|
||
this.cancelDraftSave()
|
||
this.persistDraft(true)
|
||
},
|
||
|
||
onSelectedProductImageError() {
|
||
this.setData({ 'selectedProduct.coverImage': '' })
|
||
},
|
||
|
||
back() {
|
||
wx.navigateBack()
|
||
}
|
||
})
|