const planningApi = require('../../api/planning') const productsApi = require('../../api/products') const tagsApi = require('../../api/tags') const customersApi = require('../../api/customers') const dateUtil = require('../../utils/date') const { markPlanningRefresh } = require('../../utils/planning-refresh') const { chooseImageFilePaths, uploadObjectFile, resolveUploadedImagePreviewUrl } = require('../../utils/upload') const DRAFT_STORAGE_PREFIX = 'managerAppointmentDraft' const PLANNING_RETURN_TARGET_STORAGE_KEY = 'planningReturnTarget' 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 const ARTIST_FALLBACK_COLORS = ['#7AA9C2', '#8EB99B', '#BDA7D8', '#D7B17D', '#D98D8D'] const ARTIST_PRESET_LABELS = { EVERYDAY: '每天', DOUBLE_REST: '双休', SINGLE_REST: '单休', NINE_TO_FIVE: '朝九晚五', LATE_SHIFT: '晚班', CUSTOM: '自定义' } function buildClientRequestId(prefix) { return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}` } 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) { const timeText = artist.scheduleTimeSummary || buildArtistTimeSummary(artist, schedule) 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) { 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 } 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}`) } } 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}`)) }) }) } function normalizeDuration(value) { const duration = Number(value) return Number.isFinite(duration) && duration > 0 ? Math.floor(duration) : 0 } 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}` } 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)) } 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 } 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) return { startMinute, endMinute: resolveAppointmentAbsoluteEndMinute(item, form.appointmentDate, startMinute) } }) } 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 } 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 } 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 '' } 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() } function splitTimeValue(value) { const parts = String(value || '').split(':') return { hour: parts[0] || '', minute: parts[1] || '' } } function buildTimePickerState(selectedValue) { const hourValues = [] const minuteValues = [] for (let hour = 0; hour < 24; hour += 1) { hourValues.push(String(hour).padStart(2, '0')) } for (let minute = 0; minute < 60; minute += 1) { minuteValues.push(String(minute).padStart(2, '0')) } const selectedParts = splitTimeValue(selectedValue) const selectedHour = hourValues.includes(selectedParts.hour) ? selectedParts.hour : hourValues[0] const selectedMinute = minuteValues.includes(selectedParts.minute) ? selectedParts.minute : minuteValues[0] const value = `${selectedHour}:${selectedMinute}` return { hourValues, minuteValues, value, indices: [hourValues.indexOf(selectedHour), minuteValues.indexOf(selectedMinute)] } } function resolveInitialTimePickerValue(form) { if (form.appointmentTime) { return form.appointmentTime } if (!isToday(form.appointmentDate)) { return '00:00' } return dateUtil.timeFromMinutes(Math.min(DAY_MINUTES - 1, getCurrentMinuteOfDay() + 1)) } function resolveTimeConfirmTip(form) { if (!form.appointmentDate) { return '请先选择预约日期' } if (!form.artistId) { return '请先选择美甲师' } if (!normalizeDuration(form.durationMinutes)) { return '请先填写预约时长' } return '' } function buildAvailableTimeGroups(calendar, form, durationMinutes) { const daySummary = findDaySummary(calendar, form.appointmentDate) if (daySummary && daySummary.dayStatus === 'rest') { return [] } 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( dateUtil.minutesOfDay(extractTimeText(schedule.startTime)), businessStartTime ? dateUtil.minutesOfDay(extractTimeText(businessStartTime)) : 0 ) 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)) { 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}分钟` : '') const productPrice = formatProductPrice(product.price) const productPriceText = productPrice === '0' ? '未定' : productPrice ? `¥${productPrice}` : '价格待定' return { ...product, coverImage: imageUrls[0] || '', tagList: parseProductTags(product).slice(0, 4), artistText: artistNames.length > 0 ? artistNames.join('、') : '全部美甲师', 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 } } 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 resolveTagPickerIndex(tagOptions, value) { const firstTag = String(value || '').split(/[;,,、]/)[0].trim() if (!firstTag) { return 0 } const index = tagOptions.findIndex(item => item.name === firstTag) return index >= 0 ? index : 0 } function resolveTagValue(tagOptions, value) { const tokens = String(value || '') .split(/[;,,、]/) .map(item => item.trim()) .filter(Boolean) if (tokens.length === 0) { return '' } if (!Array.isArray(tagOptions) || tagOptions.length === 0) { return '' } const matched = tokens .map(token => tagOptions.find(item => item.name === token)) .find(Boolean) return matched ? matched.name : '' } 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) } 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) } function resolveAppointmentPriceText(form) { if (form.manualProductPriceUndetermined) { return '0' } return normalizeConfirmedPrice(form.manualProductPrice) } 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 || '未填写手机号' } } 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 } } Page({ data: { form: { customerUserId: '', customerName: '', phone: '', appointmentDate: dateUtil.formatDate(new Date()), appointmentTime: '', productId: '', manualProductTitle: '', manualProductPrice: '', manualProductPriceUndetermined: false, manualProductDescription: '', manualProductTags: '', manualProductPrecautions: '', manualProductImageFileIds: '', manualProductImageUrl: '', durationMinutes: '', artistId: '', depositPaid: false, needRemoval: false, fromMeituan: false, remark: '' }, customerOptions: [], customerDropdownVisible: false, customerNameFocused: false, customerLoading: false, customerError: '', products: [], filteredProducts: [], productsLoaded: false, productsLoading: false, artists: [], selectedProduct: {}, selectedArtist: {}, artistSheetVisible: false, pendingArtistId: '', productModalVisible: false, manualProductPanelVisible: false, manualProductImageUrls: [], productKeyword: '', productError: '', tagOptions: [], tagsLoaded: false, tagsLoading: false, tagPickerIndex: 0, tagError: '', conflictTip: '', conflictLevel: 'free', canCreateAppointment: true, draftSavedAtText: '', manualImageUploading: false, timeSheetVisible: false, timeSelectTip: '请选择预约时间', timePickerHours: [], timePickerMinutes: [], timePickerIndices: [0, 0], timePickerValue: '', timePickerConfirming: false, pageMaskVisible: false, pageMaskText: '', loading: false }, onLoad(options) { const creatable = canCreateAppointment() const draftForm = creatable ? readDraftForm() : null const initialForm = buildInitialAppointmentForm(this.data.form, draftForm, options) this.setData({ canCreateAppointment: creatable, form: initialForm, manualProductImageUrls: splitManualImageValues(initialForm.manualProductImageUrl || ''), draftSavedAtText: draftForm ? '已恢复本机草稿' : '' }) if (!creatable) { wx.showToast({ title: '美甲师账号只能查看预约', icon: 'none' }) return } this.loadOptions() wx.nextTick(() => { this.setData({ customerNameFocused: true }) }) }, showPageMask(text) { this.setData({ pageMaskVisible: true, pageMaskText: text }) }, hidePageMask() { this.setData({ pageMaskVisible: false, pageMaskText: '' }) }, async loadOptions() { this.showPageMask('正在加载预约信息') try { await this.loadArtists() this.refreshAvailableTimes() await this.checkAvailability(this.data.form.appointmentTime) } finally { this.hidePageMask() } }, 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, 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() { 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' }) } }, onInput(event) { const field = event.currentTarget.dataset.field const value = field === 'manualProductPrice' ? sanitizePriceInput(event.detail.value) : event.detail.value const patch = { [`form.${field}`]: value } if (field === 'manualProductPrice' && value) { patch['form.manualProductPriceUndetermined'] = false } if (field === 'customerName' || field === 'phone') { patch['form.customerUserId'] = '' patch.customerDropdownVisible = true } this.setData(patch) if (field === 'customerName' || field === 'phone') { this.scheduleCustomerSearch(field) } if (field === 'durationMinutes') { this.refreshAvailableTimes() this.checkAvailability() } return value }, toggleFlag(event) { const field = event.currentTarget.dataset.field this.setData({ [`form.${field}`]: !this.data.form[field] }) }, onPriceUndeterminedChange(event) { const checked = !!event.detail.value const patch = { 'form.manualProductPriceUndetermined': checked } if (checked) { patch['form.manualProductPrice'] = '' } this.setData(patch) }, onCustomerFocus(event) { const field = event.currentTarget.dataset.field this.setData({ customerDropdownVisible: true, customerNameFocused: field === 'customerName' }) 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 } 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 } this.setData({ 'form.customerUserId': customer.id, 'form.customerName': customer.name, 'form.phone': customer.phone, customerDropdownVisible: false }) }, hideCustomerDropdown() { setTimeout(() => { this.setData({ customerDropdownVisible: false, customerNameFocused: false }) }, 180) }, onUnload() { if (this._customerTimer) { clearTimeout(this._customerTimer) } }, async onDateChange(event) { 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() } }, 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() { 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() { this.setData({ productModalVisible: false }) }, async openManualProductPanel() { 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() } const imageUrls = this.data.manualProductImageUrls.length > 0 ? this.data.manualProductImageUrls : splitManualImageValues(this.data.form.manualProductImageUrl) const productTitle = String(this.data.form.manualProductTitle || '').trim() const patch = { manualProductPanelVisible: true, productModalVisible: false, manualProductImageUrls: imageUrls, tagPickerIndex: resolveTagPickerIndex(this.data.tagOptions, this.data.form.manualProductTags) } if (!productTitle) { patch['form.manualProductTitle'] = customerName } this.setData({ ...patch }) }, 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) const priceUndetermined = price === '' || price === '0' const productTag = resolveTagValue(this.data.tagOptions, parseProductTags(selectedProduct).join(',')) const imageUrls = Array.isArray(selectedProduct.imageUrls) ? selectedProduct.imageUrls : [] this.setData({ selectedProduct, 'form.productId': '', 'form.manualProductTitle': selectedProduct.title || '', '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, tagPickerIndex: resolveTagPickerIndex(this.data.tagOptions, productTag), 'form.durationMinutes': String(parseInt(selectedProduct.approximateDuration, 10) || this.data.form.durationMinutes || '') }) this.refreshAvailableTimes() this.checkAvailability() }, onManualTagChange(event) { const tag = this.data.tagOptions[Number(event.detail.value)] if (!tag) { return } this.setData({ tagPickerIndex: Number(event.detail.value), 'form.manualProductTags': tag.name }) }, useManualProduct() { const title = String(this.data.form.manualProductTitle || '').trim() const priceUndetermined = !!this.data.form.manualProductPriceUndetermined const priceText = resolveAppointmentPriceText(this.data.form) if (!title) { wx.showToast({ title: '请填写作品名称', icon: 'none' }) return } if (!priceText) { wx.showToast({ title: '请填写正确的作品价格', icon: 'none' }) return } this.setData({ selectedProduct: {}, 'form.productId': '', 'form.manualProductTitle': title, 'form.manualProductPrice': priceUndetermined ? '' : priceText, manualProductPanelVisible: false }) this.closeProductModal() this.refreshAvailableTimes() void this.checkAvailability(this.data.form.appointmentTime) }, async chooseManualProductImage() { if (this.data.manualImageUploading) { return } 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 } try { const filePaths = await chooseImageFilePaths(remainingCount) if (filePaths.length === 0) { return } this.setData({ manualImageUploading: true }) 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 const fileUrl = resolveUploadedImagePreviewUrl(uploadResult, filePath) if (!fileId) { throw new Error('作品图片上传成功但未返回文件ID') } nextFileIds.push(String(fileId)) nextImageUrls.push(fileUrl) } this.setData({ 'form.manualProductImageFileIds': nextFileIds.join(','), 'form.manualProductImageUrl': nextImageUrls.join(','), manualProductImageUrls: nextImageUrls }) } catch (error) { wx.showToast({ title: error.message || '图片上传失败', icon: 'none' }) } finally { this.setData({ manualImageUploading: false }) } }, 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) this.setData({ 'form.manualProductImageFileIds': nextFileIds.join(','), 'form.manualProductImageUrl': nextImageUrls.join(','), manualProductImageUrls: nextImageUrls }) }, onArtistChange(event) { const selectedArtist = this.data.artists[Number(event.detail.value)] || {} 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) { this.setData({ selectedArtist, 'form.artistId': selectedArtist.id, 'form.appointmentTime': '', artistSheetVisible: false, pendingArtistId: '' }) this.refreshAvailableTimes() void this.checkAvailability(this.data.form.appointmentTime) }, canOpenTimeSheet() { const form = this.data.form return Boolean(form.appointmentDate) }, refreshAvailableTimes() { const form = this.data.form if (!form.appointmentDate) { this.setData({ timeSelectTip: '请选择预约时间', timePickerHours: [], timePickerMinutes: [], timePickerIndices: [0, 0], timePickerValue: '' }) return } const timePickerState = buildTimePickerState(resolveInitialTimePickerValue(form)) this.setData({ timeSelectTip: '请选择预约时间', timePickerHours: timePickerState.hourValues, timePickerMinutes: timePickerState.minuteValues, timePickerIndices: timePickerState.indices, timePickerValue: timePickerState.value }) }, async openTimeSheet() { if (!this.canOpenTimeSheet()) { wx.showToast({ title: '请先选择预约日期', icon: 'none' }) return } this.setData({ timeSheetVisible: true, timePickerConfirming: false }) this.refreshAvailableTimes() }, closeTimeSheet() { this.setData({ timeSheetVisible: false, timePickerConfirming: false }) }, onTimePickerChange(event) { const value = Array.isArray(event.detail.value) ? event.detail.value : [] const hourValues = this.data.timePickerHours || [] const minuteValues = this.data.timePickerMinutes || [] const hourIndex = Math.max(0, Math.min(hourValues.length - 1, Number(value[0] || 0))) const minuteIndex = Math.max(0, Math.min(minuteValues.length - 1, Number(value[1] || 0))) const selectedHour = hourValues[hourIndex] || hourValues[0] || '00' const selectedMinute = minuteValues[minuteIndex] || minuteValues[0] || '00' const selectedValue = selectedHour && selectedMinute ? `${selectedHour}:${selectedMinute}` : '' this.setData({ timePickerIndices: [hourIndex, minuteIndex], timePickerValue: selectedValue }) }, async confirmTimeSelection() { if (this.data.timePickerConfirming) { return } const selectedTime = this.data.timePickerValue if (!selectedTime) { wx.showToast({ title: '请先选择预约时间', icon: 'none' }) return } 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, timeSheetVisible: false }) } catch (error) { this.hidePageMask() wx.showToast({ title: error.message || '时间校验失败', icon: 'none' }) } finally { this.setData({ timePickerConfirming: false }) } }, async checkAvailability(appointmentTime) { const form = this.data.form const selectedTime = appointmentTime || form.appointmentTime if (!form.appointmentDate || !selectedTime || !form.artistId) { this.setData({ conflictTip: '', conflictLevel: 'free' }) return { ok: true } } const durationMinutes = normalizeDuration(form.durationMinutes) if (!durationMinutes) { this.setData({ conflictTip: '', conflictLevel: 'free' }) return { ok: true } } const selectedForm = { ...form, appointmentTime: selectedTime } if (isPastAppointmentTime(selectedForm)) { const tip = '请选择当前时间之后的预约时间' this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } try { const calendar = await planningApi.calendar({ startDate: form.appointmentDate, endDate: resolveAppointmentCalendarEndDate(selectedForm), artistId: form.artistId }) const selectedMinute = dateUtil.minutesOfDay(selectedTime) const busyRanges = buildBusyRanges(calendar.appointments || [], selectedForm) const unavailableTip = resolveUnavailableTimeTip(calendar, selectedForm, selectedMinute, durationMinutes, busyRanges) if (unavailableTip) { const tip = unavailableTip this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } const tip = `${this.data.selectedArtist.name || '该美甲师'} ${buildTimeRangeLabel(selectedMinute, durationMinutes)} 可预约` this.setData({ conflictTip: tip, conflictLevel: 'free' }) return { ok: true, tip } } catch (error) { const tip = error.message || '排班校验失败,请稍后重试' this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } }, async submit() { if (this.data.loading || this.data.pageMaskVisible) { return } if (!this.data.canCreateAppointment) { wx.showToast({ title: '美甲师账号只能查看预约', icon: 'none' }) return } const form = this.data.form const hasManualProduct = String(form.manualProductTitle || '').trim() const customerName = String(form.customerName || '').trim() const phone = String(form.phone || '').trim() const durationMinutes = normalizeDuration(form.durationMinutes) if (!customerName || (!form.productId && !hasManualProduct) || !form.artistId) { wx.showToast({ title: '请补全预约信息', icon: 'none' }) return } const appointmentPriceText = resolveAppointmentPriceText(form) if (!appointmentPriceText) { wx.showToast({ title: '请填写本次价格', icon: 'none' }) return } const appointmentPrice = Number(appointmentPriceText) if (!durationMinutes) { wx.showToast({ title: '请填写预约时长', icon: 'none' }) return } this.showPageMask('正在校验预约信息') const availability = await this.checkAvailability(this.data.form.appointmentTime) this.hidePageMask() if (!availability.ok) { wx.showModal({ title: '当前时间不可预约', content: availability.tip || '当前时间不可预约,请重新选择可约时间', showCancel: false, confirmText: '知道了' }) return } let confirmed try { confirmed = await confirmAppointmentSubmit() } catch (error) { wx.showToast({ title: error.message || '确认提交失败', icon: 'none' }) return } if (!confirmed) { return } this.setData({ loading: true }) this.showPageMask('正在提交预约') try { const payload = { ...form, customerName, phone: phone || undefined, customerUserId: form.customerUserId ? String(form.customerUserId) : undefined, artistId: String(form.artistId), depositPaid: !!form.depositPaid, needRemoval: !!form.needRemoval, fromMeituan: !!form.fromMeituan, durationMinutes, clientRequestId: buildClientRequestId('manager-appointment') } 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 payload.manualProductDescription = String(form.manualProductDescription || '').trim() || undefined payload.manualProductTags = String(form.manualProductTags || '').trim() || undefined payload.manualProductPrecautions = String(form.manualProductPrecautions || '').trim() || undefined payload.manualProductImageFileIds = String(form.manualProductImageFileIds || '').trim() || undefined } const result = await planningApi.createAppointment(payload) removeDraftForm() writePlanningReturnTarget({ source: 'appointment-create', date: form.appointmentDate, orderItemId: result.orderItemId || result.id || '' }) markPlanningRefresh() this.showPageMask('正在返回规划页') wx.switchTab({ url: '/pages/planning/index', fail: error => { this.setData({ loading: false }) this.hidePageMask() wx.showToast({ title: `跳转规划页失败:${error.errMsg || error.message || error}`, icon: 'none' }) } }) } catch (error) { this.setData({ loading: false }) this.hidePageMask() wx.showToast({ title: error.message || '提交失败', icon: 'none' }) } }, saveDraft() { try { writeDraftForm(this.data.form) this.setData({ draftSavedAtText: '草稿已保存到本机' }) wx.showToast({ title: '草稿已保存', icon: 'success' }) } catch (error) { wx.showToast({ title: error.message || '草稿保存失败', icon: 'none' }) } }, async clearDraft() { let confirmed try { confirmed = await confirmFormAction('清空草稿', '确认清空当前本机预约草稿?', '清空', '#d98d8d') } catch (error) { wx.showToast({ title: error.message || '确认清空失败', icon: 'none' }) return } if (!confirmed) { return } try { removeDraftForm() this.setData({ draftSavedAtText: '' }) wx.showToast({ title: '草稿已清空', icon: 'success' }) } catch (error) { wx.showToast({ title: error.message || '草稿清空失败', icon: 'none' }) } }, back() { wx.navigateBack() } })