Files
JayuCloud/JY-Salon-WeChat/pages/appointment-form/index.js
T

1698 lines
55 KiB
JavaScript
Raw Normal View History

2026-06-04 16:39:06 +08:00
const planningApi = require('../../api/planning')
const productsApi = require('../../api/products')
const tagsApi = require('../../api/tags')
2026-06-26 13:32:06 +08:00
const customersApi = require('../../api/customers')
2026-06-04 16:39:06 +08:00
const dateUtil = require('../../utils/date')
2026-06-27 02:52:47 +08:00
const { markPlanningRefresh } = require('../../utils/planning-refresh')
2026-07-21 19:48:31 +08:00
const { chooseImageFilePaths, uploadObjectFile, resolveUploadedImagePreviewUrl } = require('../../utils/upload')
2026-06-27 15:19:32 +08:00
const DRAFT_STORAGE_PREFIX = 'managerAppointmentDraft'
2026-07-23 01:34:35 +08:00
const PLANNING_RETURN_TARGET_STORAGE_KEY = 'planningReturnTarget'
2026-06-27 16:12:00 +08:00
const TIME_SLOT_MINUTES = 15
const DAY_MINUTES = 24 * 60
const DAY_END_COVER_MINUTE = 23 * 60 + 59
const DAY_MS = 24 * 60 * 60 * 1000
2026-07-21 21:34:45 +08:00
const ARTIST_FALLBACK_COLORS = ['#7AA9C2', '#8EB99B', '#BDA7D8', '#D7B17D', '#D98D8D']
const ARTIST_PRESET_LABELS = {
2026-07-21 21:56:26 +08:00
EVERYDAY: '每天',
2026-07-21 21:34:45 +08:00
DOUBLE_REST: '双休',
SINGLE_REST: '单休',
NINE_TO_FIVE: '朝九晚五',
LATE_SHIFT: '晚班',
CUSTOM: '自定义'
}
const DEFAULT_TAG_STYLE = {
textColor: '#333333',
bgColor: '#FFFFFF',
borderColor: '#E5E5E5',
sortOrder: 100,
frontVisible: 1
}
const TAG_SPLIT_PATTERN = /[;,,、]/
2026-06-04 16:39:06 +08:00
function buildClientRequestId(prefix) {
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
}
2026-07-21 21:34:45 +08:00
function normalizeTimeText(value) {
return value ? String(value).slice(0, 5) : ''
}
function buildScheduleByArtist(calendar) {
const schedules = calendar && Array.isArray(calendar.schedules) ? calendar.schedules : []
return schedules.reduce((map, schedule) => {
if (schedule && schedule.artistId) {
map[String(schedule.artistId)] = schedule
}
return map
}, {})
}
function buildArtistTimeSummary(artist, schedule) {
const startTime = normalizeTimeText(schedule && schedule.startTime ? schedule.startTime : artist.workStartTime)
const endTime = normalizeTimeText(schedule && schedule.endTime ? schedule.endTime : artist.workEndTime)
return startTime && endTime ? `${startTime}-${endTime}` : ''
}
function buildArtistScheduleSummary(artist, schedule) {
2026-07-21 21:56:26 +08:00
const timeText = artist.scheduleTimeSummary || buildArtistTimeSummary(artist, schedule)
2026-07-21 21:34:45 +08:00
const mode = artist.scheduleModeSummary
|| artist.scheduleMode
|| ARTIST_PRESET_LABELS[artist.presetType]
|| (schedule ? '今日排班' : '排班未设置')
return timeText ? `${mode} ${timeText}` : mode
}
function buildArtistStatusText(artist, schedule) {
if (schedule && Number(schedule.status) !== 1) {
return '今日休息'
}
if (schedule && Number(schedule.status) === 1) {
return '今日可约'
}
return artist.statusText || (Number(artist.status) === 0 ? '休息中' : '可预约')
}
function buildArtistMetaText(artist, schedule) {
const orderCount = Number(artist.rangeCount)
if (Number.isFinite(orderCount) && orderCount > 0) {
return `今日已有 ${orderCount} 单`
}
if (schedule && Number(schedule.status) === 1) {
return '今日暂无预约'
}
if (schedule && Number(schedule.status) !== 1) {
return '可切换日期查看排班'
}
return '等待预约'
}
function normalizeArtistForCard(artist, index, scheduleByArtist) {
const name = artist.name || artist.nickname || artist.artistName || `美甲师${index + 1}`
const schedule = scheduleByArtist[String(artist.id)] || null
const statusText = buildArtistStatusText(artist, schedule)
const shortName = artist.shortName || String(name || '师').slice(-1)
return {
...artist,
name,
shortName,
avatar: artist.avatar || artist.avatarUrl || '',
color: artist.color || ARTIST_FALLBACK_COLORS[index % ARTIST_FALLBACK_COLORS.length],
scheduleSummary: buildArtistScheduleSummary(artist, schedule),
metaText: buildArtistMetaText(artist, schedule),
statusText,
statusClass: statusText.indexOf('休') >= 0 ? 'rest' : 'free'
}
}
function getCalendarArtists(calendar) {
2026-07-21 21:34:45 +08:00
const artists = calendar && Array.isArray(calendar.artists) ? calendar.artists : []
const scheduleByArtist = buildScheduleByArtist(calendar)
return artists.map((artist, index) => normalizeArtistForCard(artist, index, scheduleByArtist))
}
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
}
2026-06-27 15:19:32 +08:00
function buildDraftKey() {
const app = getApp()
const userInfo = app.globalData.userInfo || {}
return `${DRAFT_STORAGE_PREFIX}:${userInfo.id || 'guest'}:${userInfo.shopId || 'default'}`
}
function readDraftForm() {
try {
const draft = wx.getStorageSync(buildDraftKey())
return draft && draft.form ? draft.form : null
} catch (error) {
throw new Error(`读取预约草稿失败:${error.message || error}`)
}
}
function writeDraftForm(form) {
try {
wx.setStorageSync(buildDraftKey(), {
form,
savedAt: Date.now()
})
} catch (error) {
throw new Error(`保存预约草稿失败:${error.message || error}`)
}
}
function removeDraftForm() {
try {
wx.removeStorageSync(buildDraftKey())
} catch (error) {
throw new Error(`清空预约草稿失败:${error.message || error}`)
}
}
2026-07-23 01:34:35 +08:00
function writePlanningReturnTarget(target) {
try {
wx.setStorageSync(PLANNING_RETURN_TARGET_STORAGE_KEY, target)
} catch (error) {
throw new Error(`写入规划页返回目标失败:${error.message || error}`)
}
}
function confirmAppointmentSubmit() {
return new Promise((resolve, reject) => {
wx.showModal({
title: '确认提交预约',
content: '提交成功后将返回规划月视图。',
confirmText: '提交',
cancelText: '再检查',
success: result => resolve(!!result.confirm),
fail: error => reject(new Error(`打开预约确认弹窗失败:${error.errMsg || error.message || error}`))
})
})
}
function confirmFormAction(title, content, confirmText, confirmColor) {
return new Promise((resolve, reject) => {
wx.showModal({
title,
content,
cancelText: '取消',
confirmText,
confirmColor,
success: result => resolve(!!result.confirm),
fail: error => reject(new Error(`打开确认弹窗失败:${error.errMsg || error.message || error}`))
})
})
}
2026-06-27 15:19:32 +08:00
function normalizeDuration(value) {
const duration = Number(value)
return Number.isFinite(duration) && duration > 0 ? Math.floor(duration) : 0
}
2026-06-27 16:12:00 +08:00
function buildTimeRangeLabel(startMinute, durationMinutes) {
const endMinute = startMinute + durationMinutes
const endOffset = Math.floor(endMinute / DAY_MINUTES)
const endText = dateUtil.timeFromMinutes(endMinute)
if (endOffset === 0) {
return `${dateUtil.timeFromMinutes(startMinute)}-${endText}`
}
if (endOffset === 1) {
return `${dateUtil.timeFromMinutes(startMinute)}-次日${endText}`
}
return `${dateUtil.timeFromMinutes(startMinute)}-+${endOffset}天${endText}`
2026-06-27 16:12:00 +08:00
}
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 parseDateDayNumber(dateText) {
const parts = String(dateText || '').split('-').map(Number)
if (parts.length !== 3 || parts.some(value => !Number.isFinite(value))) {
throw new Error(`无效日期:${dateText}`)
}
return Math.floor(Date.UTC(parts[0], parts[1] - 1, parts[2]) / DAY_MS)
}
function dateOffset(baseDate, targetDate) {
return parseDateDayNumber(targetDate) - parseDateDayNumber(baseDate)
}
function resolveDateByOffset(baseDate, offset) {
return dateUtil.formatDate(dateUtil.addDays(baseDate, offset))
}
2026-06-27 16:12:00 +08:00
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 resolveCoverageEndMinute(timeText) {
const minute = dateUtil.minutesOfDay(extractTimeText(timeText))
return minute >= DAY_END_COVER_MINUTE ? DAY_MINUTES : minute
}
function resolveAppointmentAbsoluteStartMinute(item, baseDate) {
return dateOffset(baseDate, normalizeAppointmentDate(item)) * DAY_MINUTES + resolveAppointmentStartMinute(item)
}
function resolveAppointmentAbsoluteEndMinute(item, baseDate, startMinute) {
if (item.endTime) {
const endText = String(item.endTime)
if (/^\d{4}-\d{2}-\d{2}/.test(endText)) {
const absoluteEndMinute = dateOffset(baseDate, endText.slice(0, 10)) * DAY_MINUTES + dateUtil.minutesOfDay(extractTimeText(endText))
return absoluteEndMinute <= startMinute ? startMinute + Number(item.durationMinutes || 0) : absoluteEndMinute
}
}
if (item.durationMinutes && Number(item.durationMinutes) > 0) {
return startMinute + Number(item.durationMinutes)
}
const localEndMinute = resolveAppointmentEndMinute(item, startMinute % DAY_MINUTES)
const absoluteEndMinute = Math.floor(startMinute / DAY_MINUTES) * DAY_MINUTES + localEndMinute
return absoluteEndMinute <= startMinute ? absoluteEndMinute + DAY_MINUTES : absoluteEndMinute
}
2026-06-27 16:12:00 +08:00
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 => !isCancelledAppointment(item))
.map(item => {
const startMinute = resolveAppointmentAbsoluteStartMinute(item, form.appointmentDate)
2026-06-27 16:12:00 +08:00
return {
startMinute,
endMinute: resolveAppointmentAbsoluteEndMinute(item, form.appointmentDate, startMinute)
2026-06-27 16:12:00 +08:00
}
})
}
function hasBusyConflict(startMinute, endMinute, ranges) {
return ranges.some(range => startMinute < range.endMinute && endMinute > range.startMinute)
}
function splitWindowSegments(appointmentDate, startMinute, durationMinutes) {
const segments = []
const endMinute = startMinute + durationMinutes
let cursor = startMinute
while (cursor < endMinute) {
const offset = Math.floor(cursor / DAY_MINUTES)
const nextDayMinute = (offset + 1) * DAY_MINUTES
const segmentEndAbsoluteMinute = Math.min(endMinute, nextDayMinute)
segments.push({
date: resolveDateByOffset(appointmentDate, offset),
startMinute: cursor - offset * DAY_MINUTES,
endMinute: segmentEndAbsoluteMinute === nextDayMinute ? DAY_MINUTES : segmentEndAbsoluteMinute - offset * DAY_MINUTES
})
cursor = segmentEndAbsoluteMinute
2026-07-01 02:08:51 +08:00
}
return segments
}
function resolveAppointmentCalendarEndDate(form) {
const durationMinutes = normalizeDuration(form.durationMinutes)
if (!form.appointmentDate || !durationMinutes) {
return form.appointmentDate
}
const latestCandidateStartMinute = DAY_MINUTES - TIME_SLOT_MINUTES
const endOffset = Math.floor((latestCandidateStartMinute + durationMinutes - 1) / DAY_MINUTES)
return resolveDateByOffset(form.appointmentDate, Math.max(0, endOffset))
}
function findDaySummary(calendar, date) {
return (calendar.daySummaries || []).find(item => item.date === date)
}
function isBusinessSegmentAvailable(calendar, segment) {
const daySummary = findDaySummary(calendar, segment.date)
if (daySummary && daySummary.dayStatus === 'rest') {
return false
}
const businessStartTime = (daySummary && daySummary.businessStartTime) || calendar.businessStartTime
const businessEndTime = (daySummary && daySummary.businessEndTime) || calendar.businessEndTime
const businessStartMinute = businessStartTime ? dateUtil.minutesOfDay(extractTimeText(businessStartTime)) : segment.startMinute
const businessEndMinute = businessEndTime ? resolveCoverageEndMinute(businessEndTime) : segment.endMinute
return segment.startMinute >= businessStartMinute && segment.endMinute <= businessEndMinute
}
function isScheduleSegmentAvailable(calendar, form, segment) {
return (calendar.schedules || [])
.filter(item => String(item.artistId) === String(form.artistId))
.filter(item => item.date === segment.date)
.filter(item => item.status === 1 && Number(item.capacity === undefined ? 1 : item.capacity) >= 1)
.some(schedule => {
const scheduleStartMinute = dateUtil.minutesOfDay(extractTimeText(schedule.startTime))
const scheduleEndMinute = resolveCoverageEndMinute(schedule.endTime)
return segment.startMinute >= scheduleStartMinute && segment.endMinute <= scheduleEndMinute
})
}
function isWindowAvailable(calendar, form, startMinute, durationMinutes, busyRanges) {
const endMinute = startMinute + durationMinutes
if (hasBusyConflict(startMinute, endMinute, busyRanges)) {
return false
}
const segments = splitWindowSegments(form.appointmentDate, startMinute, durationMinutes)
for (let index = 0; index < segments.length; index += 1) {
const segment = segments[index]
if (!isBusinessSegmentAvailable(calendar, segment) || !isScheduleSegmentAvailable(calendar, form, segment)) {
return false
}
}
return true
2026-07-01 02:08:51 +08:00
}
2026-07-23 14:50:37 +08:00
function formatDayEndMinute(minute) {
return minute >= DAY_MINUTES ? '24:00' : dateUtil.timeFromMinutes(minute)
}
function formatSegmentRange(segment) {
return `${segment.date} ${dateUtil.timeFromMinutes(segment.startMinute)}-${formatDayEndMinute(segment.endMinute)}`
}
function resolveBusinessUnavailableTip(calendar, segment) {
const daySummary = findDaySummary(calendar, segment.date)
if (daySummary && daySummary.dayStatus === 'rest') {
return `${segment.date} 为店铺休息日`
}
const businessStartTime = (daySummary && daySummary.businessStartTime) || calendar.businessStartTime
const businessEndTime = (daySummary && daySummary.businessEndTime) || calendar.businessEndTime
const businessStartMinute = businessStartTime ? dateUtil.minutesOfDay(extractTimeText(businessStartTime)) : segment.startMinute
const businessEndMinute = businessEndTime ? resolveCoverageEndMinute(businessEndTime) : segment.endMinute
if (segment.startMinute < businessStartMinute || segment.endMinute > businessEndMinute) {
return `预约时间不在门店营业时间内(${segment.date} 营业时间 ${dateUtil.timeFromMinutes(businessStartMinute)}-${formatDayEndMinute(businessEndMinute)})`
}
return ''
}
function resolveScheduleUnavailableTip(calendar, form, segment) {
const schedules = (calendar.schedules || [])
.filter(item => String(item.artistId) === String(form.artistId))
.filter(item => item.date === segment.date)
const activeSchedules = schedules
.filter(item => item.status === 1 && Number(item.capacity === undefined ? 1 : item.capacity) >= 1)
if (activeSchedules.length === 0) {
return `该美甲师 ${segment.date} 没有可预约排班`
}
const covered = activeSchedules.some(schedule => {
const scheduleStartMinute = dateUtil.minutesOfDay(extractTimeText(schedule.startTime))
const scheduleEndMinute = resolveCoverageEndMinute(schedule.endTime)
return segment.startMinute >= scheduleStartMinute && segment.endMinute <= scheduleEndMinute
})
return covered ? '' : `该美甲师排班未覆盖 ${formatSegmentRange(segment)}`
}
function resolveUnavailableTimeTip(calendar, form, startMinute, durationMinutes, busyRanges) {
const segments = splitWindowSegments(form.appointmentDate, startMinute, durationMinutes)
for (let index = 0; index < segments.length; index += 1) {
const segment = segments[index]
const businessTip = resolveBusinessUnavailableTip(calendar, segment)
if (businessTip) {
return businessTip
}
const scheduleTip = resolveScheduleUnavailableTip(calendar, form, segment)
if (scheduleTip) {
return scheduleTip
}
}
if (hasBusyConflict(startMinute, startMinute + durationMinutes, busyRanges)) {
return `该时间段已被其他预约占用(${buildTimeRangeLabel(startMinute, durationMinutes)})`
}
return ''
}
2026-07-21 13:57:43 +08:00
function getCurrentMinuteOfDay() {
const now = new Date()
return now.getHours() * 60 + now.getMinutes()
}
function isToday(dateText) {
return dateText === dateUtil.formatDate(new Date())
}
function isPastAppointmentTime(form) {
if (!form.appointmentDate || !form.appointmentTime || !isToday(form.appointmentDate)) {
return false
}
return dateUtil.minutesOfDay(form.appointmentTime) <= getCurrentMinuteOfDay()
}
function canUseTimeMinute(form, minute) {
if (!isToday(form.appointmentDate)) {
return true
}
return minute > getCurrentMinuteOfDay()
}
2026-07-23 14:50:37 +08:00
function resolveInitialTimePickerValue(form) {
if (form.appointmentTime) {
2026-07-23 17:49:43 +08:00
return normalizeTimeText(form.appointmentTime)
2026-07-23 14:50:37 +08:00
}
2026-07-23 17:49:43 +08:00
return '00:00'
2026-07-23 14:50:37 +08:00
}
function resolveTimeConfirmTip(form) {
if (!form.appointmentDate) {
return '请先选择预约日期'
}
if (!form.artistId) {
return '请先选择美甲师'
}
if (!normalizeDuration(form.durationMinutes)) {
return '请先填写预约时长'
}
return ''
2026-07-21 13:57:43 +08:00
}
2026-06-27 16:12:00 +08:00
function buildAvailableTimeGroups(calendar, form, durationMinutes) {
const daySummary = findDaySummary(calendar, form.appointmentDate)
2026-07-01 02:08:51 +08:00
if (daySummary && daySummary.dayStatus === 'rest') {
return []
}
2026-06-27 16:12:00 +08:00
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 groupMap = {
morning: { key: 'morning', title: '上午', times: [] },
afternoon: { key: 'afternoon', title: '下午', times: [] },
evening: { key: 'evening', title: '晚上', times: [] }
}
schedules.forEach(schedule => {
const businessStartTime = (daySummary && daySummary.businessStartTime) || calendar.businessStartTime
const businessEndTime = (daySummary && daySummary.businessEndTime) || calendar.businessEndTime
const scheduleStart = Math.max(
2026-07-01 02:08:51 +08:00
dateUtil.minutesOfDay(extractTimeText(schedule.startTime)),
businessStartTime ? dateUtil.minutesOfDay(extractTimeText(businessStartTime)) : 0
2026-07-01 02:08:51 +08:00
)
const scheduleEnd = Math.min(
resolveCoverageEndMinute(schedule.endTime),
businessEndTime ? resolveCoverageEndMinute(businessEndTime) : DAY_MINUTES
)
for (let minute = scheduleStart; minute < scheduleEnd; minute += TIME_SLOT_MINUTES) {
if (canUseTimeMinute(form, minute) && isWindowAvailable(calendar, form, minute, durationMinutes, busyRanges)) {
2026-06-27 16:12:00 +08:00
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 flattenTimeGroups(groups) {
return (groups || []).reduce((list, group) => list.concat(group.times || []), [])
}
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}分钟` : '')
2026-07-23 01:34:35 +08:00
const productPrice = formatProductPrice(product.price)
const productPriceText = productPrice === '0'
? '未定'
: productPrice ? `¥${productPrice}` : '价格待定'
return {
...product,
coverImage: imageUrls[0] || '',
allTags: parseProductTags(product),
tagList: parseProductTags(product).slice(0, 4),
artistText: artistNames.length > 0 ? artistNames.join('、') : '全部美甲师',
2026-07-23 01:34:35 +08:00
priceText: productPriceText,
durationText
}
}
function normalizeTagOption(tag) {
const name = String((tag && (tag.displayName || tag.tagName || tag.name)) || '').trim()
if (!name) {
return null
}
return {
id: (tag && tag.id) || name,
name,
tagName: (tag && tag.tagName) || name,
displayName: (tag && tag.displayName) || name,
textColor: (tag && tag.textColor) || DEFAULT_TAG_STYLE.textColor,
bgColor: (tag && tag.bgColor) || DEFAULT_TAG_STYLE.bgColor,
borderColor: (tag && tag.borderColor) || DEFAULT_TAG_STYLE.borderColor
}
}
function normalizeTagOptions(tags) {
const source = Array.isArray(tags) ? tags : []
const names = new Set()
return source
.map(normalizeTagOption)
.filter(Boolean)
.filter(item => {
if (names.has(item.name)) {
return false
}
names.add(item.name)
return true
})
}
function splitTagValues(value) {
return String(value || '')
.split(TAG_SPLIT_PATTERN)
.map(item => item.trim())
.filter(Boolean)
}
function encodeTagValues(tags) {
const names = new Set()
return (Array.isArray(tags) ? tags : [])
.map(item => String(item || '').trim())
.filter(Boolean)
.filter(item => {
if (names.has(item)) {
return false
}
names.add(item)
return true
})
.join(';')
}
function buildSelectableTagOptions(tagOptions, value) {
const selected = new Set(splitTagValues(value))
return (Array.isArray(tagOptions) ? tagOptions : [])
.map(normalizeTagOption)
.filter(Boolean)
.map(item => ({
...item,
selected: selected.has(item.name)
}))
}
function findTagOptionByName(tagOptions, value) {
const tagName = String(value || '').trim()
if (!tagName) {
return null
}
return (Array.isArray(tagOptions) ? tagOptions : [])
.map(normalizeTagOption)
.filter(Boolean)
.find(item => item.name === tagName) || null
}
function resolveTagPickerIndex(tagOptions, value) {
const firstTag = splitTagValues(value)[0] || ''
if (!firstTag) {
return 0
}
const index = tagOptions.findIndex(item => item.name === firstTag)
return index >= 0 ? index : 0
}
function resolveTagValue(tagOptions, value) {
return encodeTagValues(splitTagValues(value))
}
function toggleTagValue(value, tagName) {
const current = splitTagValues(value)
if (current.includes(tagName)) {
return encodeTagValues(current.filter(item => item !== tagName))
}
return encodeTagValues(current.concat(tagName))
}
function appendTagValue(value, tagName) {
return encodeTagValues(splitTagValues(value).concat(tagName))
}
function resolveCurrentShopId() {
const app = getApp()
const userInfo = (app && app.globalData && app.globalData.userInfo) || {}
return userInfo.shopId || (app && app.globalData && app.globalData.shopId) || ''
}
function buildTagCreatePayload(tagName) {
const shopId = resolveCurrentShopId()
const payload = {
tagName,
textColor: DEFAULT_TAG_STYLE.textColor,
bgColor: DEFAULT_TAG_STYLE.bgColor,
borderColor: DEFAULT_TAG_STYLE.borderColor,
sortOrder: DEFAULT_TAG_STYLE.sortOrder,
frontVisible: DEFAULT_TAG_STYLE.frontVisible
}
if (shopId) {
payload.shopId = shopId
}
return payload
}
2026-07-21 12:09:28 +08:00
function splitManualImageValues(value) {
return String(value || '')
.split(',')
.map(item => item.trim())
.filter(Boolean)
}
function formatProductPrice(value) {
if (value === undefined || value === null || value === '') {
return ''
}
const price = Number(value)
if (!Number.isFinite(price) || price < 0) {
return ''
}
return String(price)
}
2026-07-21 19:09:43 +08:00
function sanitizePriceInput(value) {
const rawValue = String(value || '')
let nextValue = ''
let hasDot = false
for (let index = 0; index < rawValue.length; index += 1) {
const char = rawValue[index]
if (char >= '0' && char <= '9') {
nextValue += char
continue
}
if (char === '.' && !hasDot) {
nextValue += char
hasDot = true
}
}
if (nextValue.startsWith('.')) {
return `0${nextValue}`
}
return nextValue
}
function normalizeConfirmedPrice(value) {
const priceText = sanitizePriceInput(value).trim()
if (!/^\d+(\.\d+)?$/.test(priceText)) {
return ''
}
const price = Number(priceText)
if (!Number.isFinite(price) || price < 0) {
return ''
}
return String(price)
}
2026-07-23 01:34:35 +08:00
function resolveAppointmentPriceText(form) {
if (form.manualProductPriceUndetermined) {
return '0'
}
return normalizeConfirmedPrice(form.manualProductPrice)
2026-07-21 19:09:43 +08:00
}
2026-06-26 13:32:06 +08:00
function normalizeCustomer(customer) {
const name = customer.nickname || customer.name || customer.account || ''
const phone = customer.contactPhone || customer.phone || ''
return {
id: customer.id,
name,
phone,
displayName: name || phone || '客户',
displayPhone: phone || '未填写手机号'
}
}
2026-07-22 20:28:54 +08:00
function buildInitialAppointmentForm(defaultForm, draftForm, options) {
const baseForm = draftForm || {}
const optionCustomerName = options.customerName ? decodeURIComponent(options.customerName) : ''
const optionPhone = options.phone ? decodeURIComponent(options.phone) : ''
const optionDate = options.date || ''
const optionArtistId = options.artistId || ''
const baseArtistId = baseForm.artistId || ''
const appointmentDate = optionDate || baseForm.appointmentDate || dateUtil.formatDate(new Date())
const artistId = optionArtistId || baseArtistId
const shouldClearCustomerUserId = Boolean(optionCustomerName || optionPhone)
const shouldClearAppointmentTime = Boolean(
(optionDate && optionDate !== baseForm.appointmentDate) ||
(optionArtistId && String(optionArtistId) !== String(baseArtistId))
)
return {
...defaultForm,
...baseForm,
customerUserId: shouldClearCustomerUserId ? '' : (baseForm.customerUserId || ''),
customerName: optionCustomerName || baseForm.customerName || '',
phone: optionPhone || baseForm.phone || '',
appointmentDate,
appointmentTime: shouldClearAppointmentTime ? '' : (baseForm.appointmentTime || ''),
artistId
}
}
2026-06-04 16:39:06 +08:00
Page({
data: {
form: {
2026-06-26 13:32:06 +08:00
customerUserId: '',
2026-06-04 16:39:06 +08:00
customerName: '',
phone: '',
appointmentDate: dateUtil.formatDate(new Date()),
2026-06-27 16:12:00 +08:00
appointmentTime: '',
2026-06-04 16:39:06 +08:00
productId: '',
manualProductTitle: '',
manualProductPrice: '',
2026-07-23 01:34:35 +08:00
manualProductPriceUndetermined: false,
2026-06-27 15:19:32 +08:00
manualProductDescription: '',
manualProductTags: '',
manualProductPrecautions: '',
manualProductImageFileIds: '',
manualProductImageUrl: '',
2026-06-04 16:39:06 +08:00
durationMinutes: '',
artistId: '',
2026-07-20 01:22:37 +08:00
depositPaid: false,
needRemoval: false,
fromMeituan: false,
2026-06-04 16:39:06 +08:00
remark: ''
},
2026-06-26 13:32:06 +08:00
customerOptions: [],
customerDropdownVisible: false,
customerNameFocused: false,
2026-06-26 13:32:06 +08:00
customerLoading: false,
customerError: '',
2026-06-04 16:39:06 +08:00
products: [],
filteredProducts: [],
productsLoaded: false,
productsLoading: false,
artists: [],
2026-06-04 16:39:06 +08:00
selectedProduct: {},
selectedArtist: {},
2026-07-21 21:34:45 +08:00
artistSheetVisible: false,
pendingArtistId: '',
productModalVisible: false,
2026-07-21 12:09:28 +08:00
manualProductPanelVisible: false,
manualProductImageUrls: [],
productKeyword: '',
2026-06-26 11:07:54 +08:00
productError: '',
tagOptions: [],
tagsLoaded: false,
tagsLoading: false,
tagPickerIndex: 0,
tagError: '',
tagCreating: false,
manualTagInput: '',
2026-06-04 16:39:06 +08:00
conflictTip: '',
conflictLevel: 'free',
canCreateAppointment: true,
2026-06-27 15:19:32 +08:00
draftSavedAtText: '',
manualImageUploading: false,
2026-07-23 14:50:37 +08:00
timeSelectTip: '请选择预约时间',
timePickerValue: '',
timePickerConfirming: false,
pageMaskVisible: false,
pageMaskText: '',
2026-06-04 16:39:06 +08:00
loading: false
},
onLoad(options) {
const creatable = canCreateAppointment()
2026-07-22 20:28:54 +08:00
const draftForm = creatable ? readDraftForm() : null
const initialForm = buildInitialAppointmentForm(this.data.form, draftForm, options)
2026-06-04 16:39:06 +08:00
this.setData({
canCreateAppointment: creatable,
2026-07-22 20:28:54 +08:00
form: initialForm,
manualProductImageUrls: splitManualImageValues(initialForm.manualProductImageUrl || ''),
2026-06-27 15:19:32 +08:00
draftSavedAtText: draftForm ? '已恢复本机草稿' : ''
2026-06-04 16:39:06 +08:00
})
if (!creatable) {
wx.showToast({ title: '美甲师账号只能查看预约', icon: 'none' })
return
}
2026-06-04 16:39:06 +08:00
this.loadOptions()
wx.nextTick(() => {
this.setData({ customerNameFocused: true })
})
2026-06-04 16:39:06 +08:00
},
2026-07-23 14:50:37 +08:00
showPageMask(text) {
this.setData({
pageMaskVisible: true,
pageMaskText: text
})
},
hidePageMask() {
this.setData({
pageMaskVisible: false,
pageMaskText: ''
})
},
2026-06-04 16:39:06 +08:00
async loadOptions() {
2026-07-23 14:50:37 +08:00
this.showPageMask('正在加载预约信息')
2026-06-04 16:39:06 +08:00
try {
2026-07-23 14:50:37 +08:00
await this.loadArtists()
this.refreshAvailableTimes()
2026-07-23 14:50:37 +08:00
await this.checkAvailability(this.data.form.appointmentTime)
} finally {
this.hidePageMask()
2026-06-04 16:39:06 +08:00
}
},
ensureProductsLoaded() {
if (this.data.productsLoaded) {
return Promise.resolve()
}
if (this._productsLoadingPromise) {
return this._productsLoadingPromise
}
this._productsLoadingPromise = this.loadProducts().finally(() => {
this._productsLoadingPromise = null
})
return this._productsLoadingPromise
},
async loadProducts() {
this.setData({ productsLoading: true })
try {
const productsData = await productsApi.list({ page: 1, size: 100 })
const products = productsData.list || productsData || []
this.setData({
products,
productsLoaded: true,
productError: ''
})
} catch (error) {
this.setData({
products: [],
filteredProducts: [],
productsLoaded: false,
productError: error.message || '作品列表加载失败'
})
} finally {
this.setData({ productsLoading: false })
}
},
ensureTagsLoaded() {
if (this.data.tagsLoaded) {
return Promise.resolve()
}
if (this._tagsLoadingPromise) {
return this._tagsLoadingPromise
}
this._tagsLoadingPromise = this.loadTags().finally(() => {
this._tagsLoadingPromise = null
})
return this._tagsLoadingPromise
},
async loadTags() {
this.setData({ tagsLoading: true })
try {
const tagsData = await tagsApi.listAll()
const tagOptions = normalizeTagOptions(tagsData.list || tagsData || [])
const selectedTag = resolveTagValue(tagOptions, this.data.form.manualProductTags)
this.setData({
tagOptions: buildSelectableTagOptions(tagOptions, selectedTag),
tagsLoaded: true,
tagPickerIndex: resolveTagPickerIndex(tagOptions, selectedTag),
'form.manualProductTags': selectedTag,
tagError: ''
})
} catch (error) {
this.setData({
tagOptions: [],
tagsLoaded: false,
tagPickerIndex: 0,
tagError: error.message || '标签加载失败'
})
} finally {
this.setData({ tagsLoading: false })
}
},
async loadArtists() {
2026-06-26 11:07:54 +08:00
try {
const calendar = await planningApi.calendar({
startDate: this.data.form.appointmentDate,
endDate: this.data.form.appointmentDate
})
const artists = getCalendarArtists(calendar)
const selectedArtist = this.data.form.artistId ? findArtist(artists, this.data.form.artistId) : {}
this.setData({ artists, selectedArtist })
this.refreshProductCards()
} catch (error) {
this.setData({
artists: [],
selectedArtist: {},
'form.artistId': '',
conflictTip: error.message || '美甲师列表加载失败',
conflictLevel: 'danger'
})
}
},
2026-06-04 16:39:06 +08:00
onInput(event) {
2026-06-26 13:32:06 +08:00
const field = event.currentTarget.dataset.field
2026-07-21 19:09:43 +08:00
const value = field === 'manualProductPrice'
? sanitizePriceInput(event.detail.value)
: event.detail.value
2026-06-26 13:32:06 +08:00
const patch = {
2026-07-21 19:09:43 +08:00
[`form.${field}`]: value
2026-06-26 13:32:06 +08:00
}
2026-07-23 01:34:35 +08:00
if (field === 'manualProductPrice' && value) {
patch['form.manualProductPriceUndetermined'] = false
}
2026-06-26 13:32:06 +08:00
if (field === 'customerName' || field === 'phone') {
patch['form.customerUserId'] = ''
patch.customerDropdownVisible = true
}
this.setData(patch)
if (field === 'customerName' || field === 'phone') {
this.scheduleCustomerSearch(field)
}
2026-06-27 16:12:00 +08:00
if (field === 'durationMinutes') {
this.refreshAvailableTimes()
this.checkAvailability()
}
2026-07-21 19:09:43 +08:00
return value
2026-06-26 13:32:06 +08:00
},
toggleFlag(event) {
2026-07-20 01:22:37 +08:00
const field = event.currentTarget.dataset.field
this.setData({
[`form.${field}`]: !this.data.form[field]
2026-07-20 01:22:37 +08:00
})
},
2026-07-23 01:34:35 +08:00
onPriceUndeterminedChange(event) {
const checked = !!event.detail.value
const patch = {
'form.manualProductPriceUndetermined': checked
}
if (checked) {
patch['form.manualProductPrice'] = ''
}
this.setData(patch)
},
2026-06-26 13:32:06 +08:00
onCustomerFocus(event) {
const field = event.currentTarget.dataset.field
this.setData({
customerDropdownVisible: true,
customerNameFocused: field === 'customerName'
})
2026-06-26 13:32:06 +08:00
this.searchCustomers(field)
},
scheduleCustomerSearch(field) {
clearTimeout(this._customerTimer)
this._customerTimer = setTimeout(() => this.searchCustomers(field), 250)
},
async searchCustomers(preferredField) {
if (!this.data.canCreateAppointment) {
return
}
const form = this.data.form
const sourceValue = preferredField === 'phone' ? form.phone : form.customerName || form.phone
const keyword = String(sourceValue || '').trim()
if (!keyword) {
this.setData({
customerOptions: [],
customerError: '',
customerLoading: false
})
return
}
2026-06-26 13:32:06 +08:00
this.setData({ customerLoading: true })
try {
const data = await customersApi.list({ keyword, page: 1, size: 20 })
const list = data.list || data || []
this.setData({
customerOptions: list.map(normalizeCustomer),
customerError: ''
})
} catch (error) {
this.setData({
customerOptions: [],
customerError: error.message || '客户列表加载失败'
})
} finally {
this.setData({ customerLoading: false })
}
},
selectCustomer(event) {
const customer = this.data.customerOptions.find(item => String(item.id) === String(event.currentTarget.dataset.id))
if (!customer) {
return
}
2026-06-04 16:39:06 +08:00
this.setData({
2026-06-26 13:32:06 +08:00
'form.customerUserId': customer.id,
'form.customerName': customer.name,
'form.phone': customer.phone,
customerDropdownVisible: false
2026-06-04 16:39:06 +08:00
})
},
2026-06-26 13:32:06 +08:00
hideCustomerDropdown() {
setTimeout(() => {
this.setData({
customerDropdownVisible: false,
customerNameFocused: false
})
2026-06-26 13:32:06 +08:00
}, 180)
},
onUnload() {
if (this._customerTimer) {
clearTimeout(this._customerTimer)
}
},
async onDateChange(event) {
2026-07-23 14:50:37 +08:00
this.showPageMask('正在切换预约日期')
try {
this.setData({
'form.appointmentDate': event.detail.value,
'form.appointmentTime': ''
})
await this.loadArtists()
await this.refreshAvailableTimes()
await this.checkAvailability(this.data.form.appointmentTime)
} finally {
this.hidePageMask()
}
2026-06-04 16:39:06 +08:00
},
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() {
2026-07-21 19:09:43 +08:00
const customerName = String(this.data.form.customerName || '').trim()
if (!customerName) {
wx.showToast({ title: '请先填写客户姓名', icon: 'none' })
return
}
void this.openManualProductPanel()
},
async openProductTemplateSheet() {
this.showPageMask('正在加载作品库')
try {
await Promise.all([this.ensureProductsLoaded(), this.ensureTagsLoaded()])
this.setData({ productKeyword: '' })
this.refreshProductCards()
this.setData({
productModalVisible: true
})
} finally {
this.hidePageMask()
}
},
closeProductModal() {
2026-07-21 12:09:28 +08:00
this.setData({
productModalVisible: false
2026-07-21 12:09:28 +08:00
})
},
async openManualProductPanel() {
2026-07-21 19:09:43 +08:00
const customerName = String(this.data.form.customerName || '').trim()
if (!customerName) {
wx.showToast({ title: '请先填写客户姓名', icon: 'none' })
return
}
this.showPageMask('正在加载作品设置')
try {
await this.ensureTagsLoaded()
} finally {
this.hidePageMask()
}
2026-07-21 12:09:28 +08:00
const imageUrls = this.data.manualProductImageUrls.length > 0
? this.data.manualProductImageUrls
: splitManualImageValues(this.data.form.manualProductImageUrl)
2026-07-21 19:09:43 +08:00
const productTitle = String(this.data.form.manualProductTitle || '').trim()
const patch = {
2026-07-21 12:09:28 +08:00
manualProductPanelVisible: true,
productModalVisible: false,
manualProductImageUrls: imageUrls,
manualTagInput: '',
tagOptions: buildSelectableTagOptions(this.data.tagOptions, this.data.form.manualProductTags),
tagPickerIndex: resolveTagPickerIndex(this.data.tagOptions, this.data.form.manualProductTags)
2026-07-21 19:09:43 +08:00
}
if (!productTitle) {
patch['form.manualProductTitle'] = customerName
}
this.setData({
...patch
2026-07-21 12:09:28 +08:00
})
},
closeManualProductPanel() {
if (this.data.manualImageUploading) {
return
}
this.setData({
manualProductPanelVisible: false,
productModalVisible: false
})
},
stopTap() {
},
onProductSearch(event) {
this.setData({ productKeyword: event.detail.value })
this.refreshProductCards()
},
selectProduct(event) {
const selectedProduct = this.data.filteredProducts.find(item => String(item.id) === String(event.currentTarget.dataset.id)) || {}
const price = formatProductPrice(selectedProduct.price)
2026-07-23 01:34:35 +08:00
const priceUndetermined = price === '' || price === '0'
const productTag = resolveTagValue(this.data.tagOptions, (selectedProduct.allTags || parseProductTags(selectedProduct)).join(','))
const imageUrls = Array.isArray(selectedProduct.imageUrls) ? selectedProduct.imageUrls : []
2026-06-04 16:39:06 +08:00
this.setData({
selectedProduct,
'form.productId': '',
'form.manualProductTitle': selectedProduct.title || '',
2026-07-23 01:34:35 +08:00
'form.manualProductPrice': priceUndetermined ? '' : price,
'form.manualProductPriceUndetermined': priceUndetermined,
'form.manualProductDescription': selectedProduct.description || '',
'form.manualProductTags': productTag,
'form.manualProductPrecautions': selectedProduct.precautions || '',
'form.manualProductImageFileIds': selectedProduct.imageFileIds || '',
'form.manualProductImageUrl': imageUrls.join(','),
manualProductImageUrls: imageUrls,
productModalVisible: false,
tagOptions: buildSelectableTagOptions(this.data.tagOptions, productTag),
tagPickerIndex: resolveTagPickerIndex(this.data.tagOptions, productTag),
2026-06-27 15:19:32 +08:00
'form.durationMinutes': String(parseInt(selectedProduct.approximateDuration, 10) || this.data.form.durationMinutes || '')
2026-06-04 16:39:06 +08:00
})
2026-06-27 16:12:00 +08:00
this.refreshAvailableTimes()
this.checkAvailability()
},
toggleManualTag(event) {
const tagName = String(event.currentTarget.dataset.name || '').trim()
if (!tagName) {
return
}
const nextValue = toggleTagValue(this.data.form.manualProductTags, tagName)
this.setData({
'form.manualProductTags': nextValue,
tagOptions: buildSelectableTagOptions(this.data.tagOptions, nextValue),
tagPickerIndex: resolveTagPickerIndex(this.data.tagOptions, nextValue)
})
},
onManualTagInput(event) {
this.setData({ manualTagInput: event.detail.value })
},
async createManualTag() {
if (this.data.tagCreating || this.data.tagsLoading) {
return
}
const tagName = String(this.data.manualTagInput || '').trim()
if (!tagName) {
wx.showToast({ title: '请输入标签名称', icon: 'none' })
return
}
const existingTag = findTagOptionByName(this.data.tagOptions, tagName)
if (existingTag) {
const nextValue = appendTagValue(this.data.form.manualProductTags, existingTag.name)
this.setData({
manualTagInput: '',
'form.manualProductTags': nextValue,
tagOptions: buildSelectableTagOptions(this.data.tagOptions, nextValue),
tagPickerIndex: resolveTagPickerIndex(this.data.tagOptions, nextValue),
tagError: ''
})
return
}
this.setData({ tagCreating: true })
try {
const createdId = await tagsApi.create(buildTagCreatePayload(tagName))
const nextOptions = normalizeTagOptions(this.data.tagOptions.concat({
id: createdId || tagName,
tagName,
displayName: tagName
}))
const nextValue = appendTagValue(this.data.form.manualProductTags, tagName)
this.setData({
manualTagInput: '',
tagOptions: buildSelectableTagOptions(nextOptions, nextValue),
tagPickerIndex: resolveTagPickerIndex(nextOptions, nextValue),
'form.manualProductTags': nextValue,
tagsLoaded: true,
tagError: ''
})
wx.showToast({ title: '标签已新增', icon: 'success' })
} catch (error) {
this.setData({ tagError: error.message || '标签新增失败' })
wx.showToast({ title: error.message || '标签新增失败', icon: 'none' })
} finally {
this.setData({ tagCreating: false })
}
},
onManualTagChange(event) {
const tag = this.data.tagOptions[Number(event.detail.value)]
if (!tag) {
return
}
const nextValue = toggleTagValue(this.data.form.manualProductTags, tag.name)
this.setData({
tagPickerIndex: Number(event.detail.value),
'form.manualProductTags': nextValue,
tagOptions: buildSelectableTagOptions(this.data.tagOptions, nextValue)
})
},
useManualProduct() {
const title = String(this.data.form.manualProductTitle || '').trim()
2026-07-23 01:34:35 +08:00
const priceUndetermined = !!this.data.form.manualProductPriceUndetermined
const priceText = resolveAppointmentPriceText(this.data.form)
2026-07-21 19:09:43 +08:00
if (!title) {
wx.showToast({ title: '请填写作品名称', icon: 'none' })
return
}
if (!priceText) {
wx.showToast({ title: '请填写正确的作品价格', icon: 'none' })
return
}
this.setData({
selectedProduct: {},
'form.productId': '',
'form.manualProductTitle': title,
2026-07-23 01:34:35 +08:00
'form.manualProductPrice': priceUndetermined ? '' : priceText,
2026-07-21 12:09:28 +08:00
manualProductPanelVisible: false
})
this.closeProductModal()
2026-06-27 16:12:00 +08:00
this.refreshAvailableTimes()
2026-07-23 14:50:37 +08:00
void this.checkAvailability(this.data.form.appointmentTime)
2026-06-04 16:39:06 +08:00
},
2026-06-27 15:19:32 +08:00
async chooseManualProductImage() {
if (this.data.manualImageUploading) {
return
}
2026-07-21 12:09:28 +08:00
const currentFileIds = splitManualImageValues(this.data.form.manualProductImageFileIds)
const currentImageUrls = this.data.manualProductImageUrls.length > 0
? this.data.manualProductImageUrls
: splitManualImageValues(this.data.form.manualProductImageUrl)
const remainingCount = 9 - currentFileIds.length
if (remainingCount <= 0) {
wx.showToast({ title: '最多上传 9 张作品图片', icon: 'none' })
return
}
2026-06-27 15:19:32 +08:00
try {
2026-07-21 12:09:28 +08:00
const filePaths = await chooseImageFilePaths(remainingCount)
if (filePaths.length === 0) {
2026-06-27 15:19:32 +08:00
return
}
this.setData({ manualImageUploading: true })
2026-07-21 12:09:28 +08:00
const nextFileIds = currentFileIds.slice()
const nextImageUrls = currentImageUrls.slice()
for (let index = 0; index < filePaths.length; index += 1) {
const filePath = filePaths[index]
const uploadResult = await uploadObjectFile(filePath)
const fileId = uploadResult.id || uploadResult.fileId
2026-07-21 19:48:31 +08:00
const fileUrl = resolveUploadedImagePreviewUrl(uploadResult, filePath)
2026-07-21 12:09:28 +08:00
if (!fileId) {
throw new Error('作品图片上传成功但未返回文件ID')
}
nextFileIds.push(String(fileId))
nextImageUrls.push(fileUrl)
2026-06-27 15:19:32 +08:00
}
this.setData({
2026-07-21 12:09:28 +08:00
'form.manualProductImageFileIds': nextFileIds.join(','),
'form.manualProductImageUrl': nextImageUrls.join(','),
manualProductImageUrls: nextImageUrls
2026-06-27 15:19:32 +08:00
})
} catch (error) {
wx.showToast({ title: error.message || '图片上传失败', icon: 'none' })
} finally {
this.setData({ manualImageUploading: false })
}
},
2026-07-21 12:09:28 +08:00
removeManualProductImage(event) {
const currentFileIds = splitManualImageValues(this.data.form.manualProductImageFileIds)
const currentImageUrls = this.data.manualProductImageUrls.length > 0
? this.data.manualProductImageUrls
: splitManualImageValues(this.data.form.manualProductImageUrl)
const index = Number(event.currentTarget.dataset.index)
if (!Number.isInteger(index) || index < 0) {
this.setData({
'form.manualProductImageFileIds': '',
'form.manualProductImageUrl': '',
manualProductImageUrls: []
})
return
}
const nextFileIds = currentFileIds.filter((item, itemIndex) => itemIndex !== index)
const nextImageUrls = currentImageUrls.filter((item, itemIndex) => itemIndex !== index)
2026-06-27 15:19:32 +08:00
this.setData({
2026-07-21 12:09:28 +08:00
'form.manualProductImageFileIds': nextFileIds.join(','),
'form.manualProductImageUrl': nextImageUrls.join(','),
manualProductImageUrls: nextImageUrls
2026-06-27 15:19:32 +08:00
})
},
2026-06-04 16:39:06 +08:00
onArtistChange(event) {
const selectedArtist = this.data.artists[Number(event.detail.value)] || {}
2026-07-21 21:34:45 +08:00
this.applyArtistSelection(selectedArtist)
},
openArtistSheet() {
this.setData({
artistSheetVisible: true,
pendingArtistId: this.data.form.artistId || ''
})
},
closeArtistSheet() {
this.setData({
artistSheetVisible: false,
pendingArtistId: ''
})
},
selectArtistCard(event) {
this.setData({ pendingArtistId: event.currentTarget.dataset.id || '' })
},
confirmArtistSheet() {
const selectedArtist = findArtist(this.data.artists, this.data.pendingArtistId)
if (!selectedArtist.id) {
wx.showToast({ title: '请选择美甲师', icon: 'none' })
return
}
this.applyArtistSelection(selectedArtist)
},
applyArtistSelection(selectedArtist) {
2026-06-04 16:39:06 +08:00
this.setData({
selectedArtist,
2026-06-27 16:12:00 +08:00
'form.artistId': selectedArtist.id,
2026-07-21 21:34:45 +08:00
'form.appointmentTime': '',
artistSheetVisible: false,
pendingArtistId: ''
2026-06-27 16:12:00 +08:00
})
this.refreshAvailableTimes()
2026-07-23 14:50:37 +08:00
void this.checkAvailability(this.data.form.appointmentTime)
2026-06-27 16:12:00 +08:00
},
2026-07-23 14:50:37 +08:00
refreshAvailableTimes() {
2026-06-27 16:12:00 +08:00
const form = this.data.form
2026-07-23 14:50:37 +08:00
if (!form.appointmentDate) {
this.setData({
timeSelectTip: '请选择预约时间',
timePickerValue: ''
})
2026-06-27 16:12:00 +08:00
return
}
this.setData({
2026-07-23 14:50:37 +08:00
timeSelectTip: '请选择预约时间',
2026-07-23 17:49:43 +08:00
timePickerValue: resolveInitialTimePickerValue(form)
2026-06-27 16:12:00 +08:00
})
},
2026-07-23 17:49:43 +08:00
async onNativeTimeChange(event) {
2026-07-23 14:50:37 +08:00
if (this.data.timePickerConfirming) {
return
}
2026-07-23 17:49:43 +08:00
const selectedTime = normalizeTimeText(event.detail.value)
2026-07-23 14:50:37 +08:00
if (!selectedTime) {
wx.showToast({ title: '请先选择预约时间', icon: 'none' })
return
}
2026-07-23 17:49:43 +08:00
this.setData({ timePickerValue: selectedTime })
2026-07-23 14:50:37 +08:00
const confirmTip = resolveTimeConfirmTip(this.data.form)
if (confirmTip) {
wx.showModal({
title: '无法确认时间',
content: confirmTip,
showCancel: false,
confirmText: '知道了'
})
return
}
this.setData({ timePickerConfirming: true })
this.showPageMask('正在校验预约时间')
try {
const availability = await this.checkAvailability(selectedTime)
this.hidePageMask()
if (!availability.ok) {
wx.showModal({
title: '当前时间不可预约',
content: availability.tip || '当前时间不可预约,请重新选择可约时间',
showCancel: false,
confirmText: '知道了'
})
await this.checkAvailability(this.data.form.appointmentTime)
return
}
this.setData({
'form.appointmentTime': selectedTime,
2026-07-23 17:49:43 +08:00
timePickerValue: selectedTime
2026-07-23 14:50:37 +08:00
})
} catch (error) {
this.hidePageMask()
wx.showToast({ title: error.message || '时间校验失败', icon: 'none' })
} finally {
this.setData({ timePickerConfirming: false })
}
},
async checkAvailability(appointmentTime) {
2026-06-04 16:39:06 +08:00
const form = this.data.form
2026-07-23 14:50:37 +08:00
const selectedTime = appointmentTime || form.appointmentTime
if (!form.appointmentDate || !selectedTime || !form.artistId) {
2026-06-04 16:39:06 +08:00
this.setData({ conflictTip: '', conflictLevel: 'free' })
return { ok: true }
}
2026-06-27 15:19:32 +08:00
const durationMinutes = normalizeDuration(form.durationMinutes)
if (!durationMinutes) {
this.setData({ conflictTip: '', conflictLevel: 'free' })
return { ok: true }
}
2026-07-23 14:50:37 +08:00
const selectedForm = { ...form, appointmentTime: selectedTime }
if (isPastAppointmentTime(selectedForm)) {
2026-07-21 13:57:43 +08:00
const tip = '请选择当前时间之后的预约时间'
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
return { ok: false, tip }
}
2026-06-04 16:39:06 +08:00
try {
const calendar = await planningApi.calendar({
startDate: form.appointmentDate,
2026-07-23 14:50:37 +08:00
endDate: resolveAppointmentCalendarEndDate(selectedForm),
artistId: form.artistId
})
2026-07-23 14:50:37 +08:00
const selectedMinute = dateUtil.minutesOfDay(selectedTime)
const busyRanges = buildBusyRanges(calendar.appointments || [], selectedForm)
const unavailableTip = resolveUnavailableTimeTip(calendar, selectedForm, selectedMinute, durationMinutes, busyRanges)
if (unavailableTip) {
const tip = unavailableTip
2026-07-01 02:08:51 +08:00
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
return { ok: false, tip }
}
2026-07-23 14:50:37 +08:00
const tip = `${this.data.selectedArtist.name || '该美甲师'} ${buildTimeRangeLabel(selectedMinute, durationMinutes)} 可预约`
2026-06-04 16:39:06 +08:00
this.setData({ conflictTip: tip, conflictLevel: 'free' })
return { ok: true, tip }
} catch (error) {
2026-06-26 11:07:54 +08:00
const tip = error.message || '排班校验失败,请稍后重试'
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
return { ok: false, tip }
2026-06-04 16:39:06 +08:00
}
},
async submit() {
2026-07-23 14:50:37 +08:00
if (this.data.loading || this.data.pageMaskVisible) {
return
}
if (!this.data.canCreateAppointment) {
wx.showToast({ title: '美甲师账号只能查看预约', icon: 'none' })
return
}
2026-06-04 16:39:06 +08:00
const form = this.data.form
2026-07-23 01:34:35 +08:00
const hasManualProduct = String(form.manualProductTitle || '').trim()
2026-07-20 01:22:37 +08:00
const customerName = String(form.customerName || '').trim()
const phone = String(form.phone || '').trim()
2026-06-27 15:19:32 +08:00
const durationMinutes = normalizeDuration(form.durationMinutes)
2026-07-20 01:22:37 +08:00
if (!customerName || (!form.productId && !hasManualProduct) || !form.artistId) {
2026-06-04 16:39:06 +08:00
wx.showToast({ title: '请补全预约信息', icon: 'none' })
return
}
2026-07-23 01:34:35 +08:00
const appointmentPriceText = resolveAppointmentPriceText(form)
2026-07-21 19:09:43 +08:00
if (!appointmentPriceText) {
wx.showToast({ title: '请填写本次价格', icon: 'none' })
return
}
2026-07-21 19:09:43 +08:00
const appointmentPrice = Number(appointmentPriceText)
2026-06-27 15:19:32 +08:00
if (!durationMinutes) {
wx.showToast({ title: '请填写预约时长', icon: 'none' })
return
}
2026-07-23 14:50:37 +08:00
this.showPageMask('正在校验预约信息')
const availability = await this.checkAvailability(this.data.form.appointmentTime)
this.hidePageMask()
2026-06-04 16:39:06 +08:00
if (!availability.ok) {
2026-07-23 14:50:37 +08:00
wx.showModal({
title: '当前时间不可预约',
content: availability.tip || '当前时间不可预约,请重新选择可约时间',
showCancel: false,
confirmText: '知道了'
})
2026-06-04 16:39:06 +08:00
return
}
2026-07-23 01:34:35 +08:00
let confirmed
try {
confirmed = await confirmAppointmentSubmit()
} catch (error) {
wx.showToast({ title: error.message || '确认提交失败', icon: 'none' })
return
}
if (!confirmed) {
return
}
2026-06-04 16:39:06 +08:00
this.setData({ loading: true })
2026-07-23 14:50:37 +08:00
this.showPageMask('正在提交预约')
2026-06-04 16:39:06 +08:00
try {
const payload = {
2026-06-04 16:39:06 +08:00
...form,
2026-07-20 01:22:37 +08:00
customerName,
phone: phone || undefined,
2026-06-26 13:32:06 +08:00
customerUserId: form.customerUserId ? String(form.customerUserId) : undefined,
artistId: String(form.artistId),
2026-07-20 01:22:37 +08:00
depositPaid: !!form.depositPaid,
needRemoval: !!form.needRemoval,
fromMeituan: !!form.fromMeituan,
2026-06-27 15:19:32 +08:00
durationMinutes,
clientRequestId: buildClientRequestId('manager-appointment')
}
2026-07-23 01:34:35 +08:00
delete payload.manualProductPriceUndetermined
if (form.productId) {
payload.productId = String(form.productId)
payload.manualProductTitle = undefined
payload.manualProductPrice = appointmentPrice
} else {
payload.productId = undefined
payload.manualProductTitle = String(form.manualProductTitle || '').trim()
payload.manualProductPrice = appointmentPrice
2026-06-27 15:19:32 +08:00
payload.manualProductDescription = String(form.manualProductDescription || '').trim() || undefined
payload.manualProductTags = resolveTagValue(this.data.tagOptions, form.manualProductTags) || undefined
2026-06-27 15:19:32 +08:00
payload.manualProductPrecautions = String(form.manualProductPrecautions || '').trim() || undefined
payload.manualProductImageFileIds = String(form.manualProductImageFileIds || '').trim() || undefined
}
const result = await planningApi.createAppointment(payload)
2026-06-27 15:19:32 +08:00
removeDraftForm()
2026-07-23 01:34:35 +08:00
writePlanningReturnTarget({
source: 'appointment-create',
date: form.appointmentDate,
orderItemId: result.orderItemId || result.id || ''
})
2026-06-27 02:52:47 +08:00
markPlanningRefresh()
2026-07-23 14:50:37 +08:00
this.showPageMask('正在返回规划页')
2026-07-23 01:34:35 +08:00
wx.switchTab({
url: '/pages/planning/index',
2026-07-23 14:50:37 +08:00
fail: error => {
this.setData({ loading: false })
this.hidePageMask()
wx.showToast({ title: `跳转规划页失败:${error.errMsg || error.message || error}`, icon: 'none' })
}
2026-07-23 01:34:35 +08:00
})
2026-06-04 16:39:06 +08:00
} catch (error) {
this.setData({ loading: false })
2026-07-23 14:50:37 +08:00
this.hidePageMask()
wx.showToast({ title: error.message || '提交失败', icon: 'none' })
2026-06-04 16:39:06 +08:00
}
},
2026-06-27 15:19:32 +08:00
saveDraft() {
try {
writeDraftForm(this.data.form)
this.setData({ draftSavedAtText: '草稿已保存到本机' })
wx.showToast({ title: '草稿已保存', icon: 'success' })
} catch (error) {
wx.showToast({ title: error.message || '草稿保存失败', icon: 'none' })
}
},
2026-07-23 01:34:35 +08:00
async clearDraft() {
let confirmed
try {
confirmed = await confirmFormAction('清空草稿', '确认清空当前本机预约草稿?', '清空', '#d98d8d')
} catch (error) {
wx.showToast({ title: error.message || '确认清空失败', icon: 'none' })
return
}
if (!confirmed) {
return
}
2026-06-27 15:19:32 +08:00
try {
removeDraftForm()
this.setData({ draftSavedAtText: '' })
wx.showToast({ title: '草稿已清空', icon: 'success' })
} catch (error) {
wx.showToast({ title: error.message || '草稿清空失败', icon: 'none' })
}
},
2026-06-04 16:39:06 +08:00
back() {
wx.navigateBack()
}
})