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 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 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 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 resolveTimeSelectTip(form, availableTimes) { if (availableTimes.length > 0) { return '请选择预约时间' } return isToday(form.appointmentDate) ? '今天暂无未来可约时间' : '当前美甲师当天暂无可约时间' } 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}分钟` : '') return { ...product, coverImage: imageUrls[0] || '', tagList: parseProductTags(product).slice(0, 4), artistText: artistNames.length > 0 ? artistNames.join('、') : '全部美甲师', priceText: product.price || product.price === 0 ? `¥${product.price}` : '价格待定', durationText } } function 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 collectManualProductImages(fileIds, imageUrls) { return splitManualImageValues(`${fileIds || ''},${imageUrls || ''}`) } 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: '', manualProductDescription: '', manualProductTags: '', manualProductPrecautions: '', manualProductImageFileIds: '', manualProductImageUrl: '', durationMinutes: '', artistId: '', depositPaid: false, needRemoval: false, fromMeituan: false, remark: '' }, customerOptions: [], customerDropdownVisible: false, customerNameFocused: false, customerLoading: false, customerError: '', products: [], filteredProducts: [], artists: [], selectedProduct: {}, selectedArtist: {}, artistSheetVisible: false, pendingArtistId: '', productModalVisible: false, manualProductPanelVisible: false, manualProductImageUrls: [], productKeyword: '', productError: '', tagOptions: [], tagPickerIndex: 0, tagError: '', conflictTip: '', conflictLevel: 'free', canCreateAppointment: true, draftSavedAtText: '', manualImageUploading: false, timeSheetVisible: false, timeLoading: false, timeError: '', timeSelectTip: '请先选择美甲师并填写时长', availableTimeGroups: [], 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() this.searchCustomers() wx.nextTick(() => { this.setData({ customerNameFocused: true }) }) }, async loadOptions() { try { const productsData = await productsApi.list({ page: 1, size: 100 }) const products = productsData.list || productsData || [] this.setData({ products, productError: '' }) } catch (error) { this.setData({ products: [], filteredProducts: [], productError: error.message || '作品列表加载失败' }) } await this.loadTags() await this.loadArtists() this.refreshProductCards() await this.refreshAvailableTimes() this.checkAvailability() }, async loadTags() { try { const tagsData = await tagsApi.listAll() const tagOptions = normalizeTagOptions(tagsData.list || tagsData || []) const selectedTag = resolveTagValue(tagOptions, this.data.form.manualProductTags) this.setData({ tagOptions, tagPickerIndex: resolveTagPickerIndex(tagOptions, selectedTag), 'form.manualProductTags': selectedTag, tagError: '' }) } catch (error) { this.setData({ tagOptions: [], tagPickerIndex: 0, tagError: error.message || '标签加载失败' }) } }, 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 === '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] }) }, 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() 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.setData({ 'form.appointmentDate': event.detail.value, 'form.appointmentTime': '' }) await this.loadArtists() await this.refreshAvailableTimes() this.checkAvailability() }, refreshProductCards() { const keyword = this.data.productKeyword.trim().toLowerCase() const products = this.data.products .map(product => normalizeProduct(product, this.data.artists)) .filter(product => { if (!keyword) return true return [product.title, product.artistText, product.priceText, product.durationText, ...(product.tagList || [])] .some(value => String(value || '').toLowerCase().includes(keyword)) }) this.setData({ filteredProducts: products }) }, openProductModal() { const customerName = String(this.data.form.customerName || '').trim() if (!customerName) { wx.showToast({ title: '请先填写客户姓名', icon: 'none' }) return } this.openManualProductPanel() }, openProductTemplateSheet() { this.setData({ productKeyword: '' }) this.refreshProductCards() this.setData({ productModalVisible: true }) }, closeProductModal() { this.setData({ productModalVisible: false }) }, openManualProductPanel() { const customerName = String(this.data.form.customerName || '').trim() if (!customerName) { wx.showToast({ title: '请先填写客户姓名', icon: 'none' }) return } 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 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': price, '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 priceText = normalizeConfirmedPrice(this.data.form.manualProductPrice) const imageValues = collectManualProductImages(this.data.form.manualProductImageFileIds, this.data.form.manualProductImageUrl) if (!title) { wx.showToast({ title: '请填写作品名称', icon: 'none' }) return } if (!priceText) { wx.showToast({ title: '请填写正确的作品价格', icon: 'none' }) return } if (imageValues.length === 0) { wx.showToast({ title: '请上传作品图片', icon: 'none' }) return } this.setData({ selectedProduct: {}, 'form.productId': '', 'form.manualProductTitle': title, 'form.manualProductPrice': priceText, manualProductPanelVisible: false }) this.closeProductModal() this.refreshAvailableTimes() this.checkAvailability() }, 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() this.checkAvailability() }, canOpenTimeSheet() { const form = this.data.form return Boolean(form.appointmentDate && form.artistId && normalizeDuration(form.durationMinutes)) }, async refreshAvailableTimes() { const form = this.data.form const durationMinutes = normalizeDuration(form.durationMinutes) const requestSeq = (this._availableTimeRequestSeq || 0) + 1 this._availableTimeRequestSeq = requestSeq if (!form.appointmentDate || !form.artistId || !durationMinutes) { const patch = { availableTimeGroups: [], timeError: '', timeSelectTip: '请先选择美甲师并填写时长' } if (form.appointmentTime) { patch['form.appointmentTime'] = '' } this.setData(patch) return } this.setData({ timeLoading: true, timeError: '', timeSelectTip: '正在计算可约时间...' }) try { const calendar = await planningApi.calendar({ startDate: form.appointmentDate, endDate: resolveAppointmentCalendarEndDate(form), artistId: form.artistId }) if (requestSeq !== this._availableTimeRequestSeq) { return } const availableTimeGroups = buildAvailableTimeGroups(calendar, form, durationMinutes) const availableTimes = flattenTimeGroups(availableTimeGroups).map(item => item.value) const patch = { availableTimeGroups, timeSelectTip: resolveTimeSelectTip(form, availableTimes) } if (form.appointmentTime && !availableTimes.includes(form.appointmentTime)) { patch['form.appointmentTime'] = '' } this.setData(patch) } catch (error) { if (requestSeq !== this._availableTimeRequestSeq) { return } this.setData({ availableTimeGroups: [], timeError: error.message || '可约时间加载失败', timeSelectTip: '可约时间加载失败' }) } finally { if (requestSeq === this._availableTimeRequestSeq) { this.setData({ timeLoading: false }) } } }, async openTimeSheet() { if (!this.canOpenTimeSheet()) { wx.showToast({ title: '请先选择美甲师并填写时长', icon: 'none' }) return } this.setData({ timeSheetVisible: true }) await this.refreshAvailableTimes() }, closeTimeSheet() { this.setData({ timeSheetVisible: false }) }, selectAvailableTime(event) { const value = event.currentTarget.dataset.value this.setData({ 'form.appointmentTime': value, timeSheetVisible: false }) this.checkAvailability() }, async checkAvailability() { const form = this.data.form if (!form.appointmentDate || !form.appointmentTime || !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 } } if (isPastAppointmentTime(form)) { const tip = '请选择当前时间之后的预约时间' this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } try { const calendar = await planningApi.calendar({ startDate: form.appointmentDate, endDate: resolveAppointmentCalendarEndDate(form), artistId: form.artistId }) const daySummary = findDaySummary(calendar, form.appointmentDate) if (daySummary && daySummary.dayStatus === 'rest') { const tip = '当前日期为店铺休息日' this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } const availableTimeGroups = buildAvailableTimeGroups(calendar, form, durationMinutes) const selectedTime = flattenTimeGroups(availableTimeGroups).find(item => item.value === form.appointmentTime) if (!selectedTime) { const tip = '当前时间不可预约,请重新选择可约时间' this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } const tip = `${this.data.selectedArtist.name || '该美甲师'} ${selectedTime.rangeText} 可预约` 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.canCreateAppointment) { wx.showToast({ title: '美甲师账号只能查看预约', icon: 'none' }) return } const form = this.data.form const hasManualProduct = String(form.manualProductTitle || '').trim() && String(form.manualProductPrice || '').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 = normalizeConfirmedPrice(form.manualProductPrice) if (!appointmentPriceText) { wx.showToast({ title: '请填写本次价格', icon: 'none' }) return } const appointmentPrice = Number(appointmentPriceText) const manualProductImages = collectManualProductImages(form.manualProductImageFileIds, form.manualProductImageUrl) if (!form.productId && manualProductImages.length === 0) { wx.showToast({ title: '请上传作品图片', icon: 'none' }) return } if (!durationMinutes) { wx.showToast({ title: '请填写预约时长', icon: 'none' }) return } const availability = await this.checkAvailability() if (!availability.ok) { wx.showToast({ title: availability.tip || '该时段已被预约', icon: 'none' }) return } this.setData({ loading: true }) 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') } 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() markPlanningRefresh() wx.redirectTo({ url: `/pages/appointment-detail/index?id=${result.orderItemId}` }) } catch (error) { wx.showToast({ title: error.message || '提交失败', icon: 'none' }) } finally { this.setData({ loading: false }) } }, saveDraft() { try { writeDraftForm(this.data.form) this.setData({ draftSavedAtText: '草稿已保存到本机' }) wx.showToast({ title: '草稿已保存', icon: 'success' }) } catch (error) { wx.showToast({ title: error.message || '草稿保存失败', icon: 'none' }) } }, clearDraft() { try { removeDraftForm() this.setData({ draftSavedAtText: '' }) wx.showToast({ title: '草稿已清空', icon: 'success' }) } catch (error) { wx.showToast({ title: error.message || '草稿清空失败', icon: 'none' }) } }, back() { wx.navigateBack() } })