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

1440 lines
51 KiB
JavaScript
Raw Normal View History

2026-06-04 16:39:06 +08:00
const planningApi = require('../../api/planning')
const productsApi = require('../../api/products')
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-06-27 15:19:32 +08:00
const { chooseImageFilePath, uploadObjectFile } = require('../../utils/upload')
const DRAFT_STORAGE_PREFIX = 'managerAppointmentDraft'
2026-06-27 16:12:00 +08:00
const TIME_SLOT_MINUTES = 15
2026-06-04 16:39:06 +08:00
function buildClientRequestId(prefix) {
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
}
function getCalendarArtists(calendar) {
return calendar && Array.isArray(calendar.artists) ? calendar.artists : []
}
function findArtist(artists, artistId) {
return artists.find(item => String(item.id) === String(artistId)) || {}
}
function canCreateAppointment() {
const app = getApp()
const userInfo = app.globalData.userInfo || {}
return Number(userInfo.type) !== 3
}
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 hasPresetOptions(options) {
return Boolean(options.customerName || options.phone || options.date || options.artistId)
}
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
}
2026-06-27 16:12:00 +08:00
function buildTimeRangeLabel(startMinute, durationMinutes) {
return `${dateUtil.timeFromMinutes(startMinute)}-${dateUtil.timeFromMinutes(startMinute + durationMinutes)}`
}
function getTimePeriod(minute) {
if (minute < 12 * 60) {
return { key: 'morning', title: '上午' }
}
if (minute < 18 * 60) {
return { key: 'afternoon', title: '下午' }
}
return { key: 'evening', title: '晚上' }
}
function normalizeAppointmentDate(item) {
return item.date || String(item.startTime || '').slice(0, 10)
}
function extractTimeText(value) {
const target = String(value || '')
if (target.includes('T')) {
return target.slice(11, 16)
}
if (target.includes(' ')) {
return target.slice(11, 16)
}
return target.slice(0, 5)
}
function resolveAppointmentStartMinute(item) {
if (item.startMinute !== undefined && item.startMinute !== null) {
return Number(item.startMinute)
}
return dateUtil.minutesOfDay(extractTimeText(item.startTime))
}
function resolveAppointmentEndMinute(item, startMinute) {
if (item.endMinute !== undefined && item.endMinute !== null) {
return Number(item.endMinute)
}
if (item.endTime) {
return dateUtil.minutesOfDay(extractTimeText(item.endTime))
}
return startMinute + Number(item.durationMinutes || 60)
}
function isCancelledAppointment(item) {
return item.status === 3 || item.statusText === '已取消'
}
function buildBusyRanges(appointments, form) {
return (appointments || [])
.filter(item => String(item.artistId) === String(form.artistId))
.filter(item => normalizeAppointmentDate(item) === form.appointmentDate)
.filter(item => !isCancelledAppointment(item))
.map(item => {
const startMinute = resolveAppointmentStartMinute(item)
return {
startMinute,
endMinute: resolveAppointmentEndMinute(item, startMinute)
}
})
}
function hasBusyConflict(startMinute, endMinute, ranges) {
return ranges.some(range => startMinute < range.endMinute && endMinute > range.startMinute)
}
function buildAvailableTimeGroups(calendar, form, durationMinutes) {
const schedules = (calendar.schedules || [])
.filter(item => String(item.artistId) === String(form.artistId))
.filter(item => item.date === form.appointmentDate)
.filter(item => item.status === 1 && Number(item.capacity === undefined ? 1 : item.capacity) >= 1)
const busyRanges = buildBusyRanges(calendar.appointments || [], form)
const groupMap = {
morning: { key: 'morning', title: '上午', times: [] },
afternoon: { key: 'afternoon', title: '下午', times: [] },
evening: { key: 'evening', title: '晚上', times: [] }
}
schedules.forEach(schedule => {
const scheduleStart = dateUtil.minutesOfDay(extractTimeText(schedule.startTime))
const scheduleEnd = dateUtil.minutesOfDay(extractTimeText(schedule.endTime))
for (let minute = scheduleStart; minute + durationMinutes <= scheduleEnd; minute += TIME_SLOT_MINUTES) {
const endMinute = minute + durationMinutes
if (!hasBusyConflict(minute, endMinute, busyRanges)) {
const period = getTimePeriod(minute)
groupMap[period.key].times.push({
value: dateUtil.timeFromMinutes(minute),
rangeText: buildTimeRangeLabel(minute, durationMinutes)
})
}
}
})
return Object.keys(groupMap)
.map(key => ({
...groupMap[key],
times: groupMap[key].times.filter((item, index, array) => array.findIndex(candidate => candidate.value === item.value) === index)
}))
.filter(group => group.times.length > 0)
}
function buildUnassignedTimeGroups(durationMinutes) {
const groupMap = {
morning: { key: 'morning', title: '上午', times: [] },
afternoon: { key: 'afternoon', title: '下午', times: [] },
evening: { key: 'evening', title: '晚上', times: [] }
}
const businessStart = dateUtil.minutesOfDay('10:00')
const businessEnd = dateUtil.minutesOfDay('22:00')
for (let minute = businessStart; minute + durationMinutes <= businessEnd; minute += TIME_SLOT_MINUTES) {
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]).filter(group => group.times.length > 0)
}
2026-06-27 16:12:00 +08:00
function flattenTimeGroups(groups) {
return (groups || []).reduce((list, group) => list.concat(group.times || []), [])
}
2026-10-20 13:29:55 +08:00
function buildTimeValues(durationMinutes) {
const values = []
const open = dateUtil.minutesOfDay('10:00')
const close = dateUtil.minutesOfDay('22:00')
for (let minute = open; minute + durationMinutes <= close; minute += TIME_SLOT_MINUTES) {
values.push(dateUtil.timeFromMinutes(minute))
}
return values
}
function buildTimePickerSlots(calendar, form, durationMinutes) {
const schedules = calendar.schedules || []
const busyRanges = form.artistId ? buildBusyRanges(calendar.appointments || [], form) : []
return buildTimeValues(durationMinutes).map(value => {
const startMinute = dateUtil.minutesOfDay(value)
const endMinute = startMinute + durationMinutes
const occupied = hasBusyConflict(startMinute, endMinute, busyRanges)
const scheduled = !form.artistId || schedules.some(schedule =>
isScheduleCoveringTime(schedule, form, startMinute, endMinute)
)
const status = occupied ? 'occupied' : scheduled ? 'available' : 'off-shift'
return {
value,
hour: Number(value.slice(0, 2)),
minute: Number(value.slice(3, 5)),
rangeText: buildTimeRangeLabel(startMinute, durationMinutes),
status,
statusText: status === 'occupied' ? '已占用' : status === 'off-shift' ? '无排班' : ''
}
})
}
function buildTimePickerGroups(slots) {
const groupMap = {
morning: { key: 'morning', title: '上午', times: [] },
afternoon: { key: 'afternoon', title: '下午', times: [] },
evening: { key: 'evening', title: '晚上', times: [] }
}
;(slots || []).forEach(slot => groupMap[getTimePeriod(dateUtil.minutesOfDay(slot.value)).key].times.push(slot))
return Object.keys(groupMap).map(key => groupMap[key]).filter(group => group.times.length > 0)
}
function buildTimeWheelState(slots, preferredTime) {
if (!slots || slots.length === 0) {
return {
timePickerHours: [],
timePickerMinutes: [],
timePickerValue: [0, 0],
selectedTimeCandidate: '',
timePickerCandidateStatus: 'off-shift'
}
}
const preferredSlot = slots.find(slot => slot.value === preferredTime) || slots.find(slot => slot.value === '14:00')
const firstAvailableSlot = slots.find(slot => slot.status === 'available')
const selectedSlot = preferredSlot && preferredSlot.status === 'available'
? preferredSlot
: firstAvailableSlot || preferredSlot || slots[0]
const hours = Array.from(new Set(slots.map(slot => slot.hour)))
const selectedHourIndex = Math.max(0, hours.indexOf(selectedSlot.hour))
const minuteValues = [0, 15, 30, 45]
const minutes = minuteValues.map(minute => {
const slot = slots.find(item => item.hour === selectedSlot.hour && item.minute === minute)
return {
value: minute,
label: String(minute).padStart(2, '0'),
status: slot ? slot.status : 'off-shift',
disabled: !slot || slot.status !== 'available'
}
})
const selectedMinuteIndex = Math.max(0, minuteValues.indexOf(selectedSlot.minute))
return {
timePickerHours: hours.map(hour => ({
value: hour,
label: String(hour).padStart(2, '0'),
disabled: !slots.some(slot => slot.hour === hour && slot.status === 'available')
})),
timePickerMinutes: minutes,
timePickerValue: [selectedHourIndex, selectedMinuteIndex],
selectedTimeCandidate: selectedSlot.value,
timePickerCandidateStatus: selectedSlot.status
}
}
function timeWheelStateForHour(slots, hour, selectedMinute) {
const minuteValues = [0, 15, 30, 45]
const minutes = minuteValues.map(minute => {
const slot = slots.find(item => item.hour === hour && item.minute === minute)
return {
value: minute,
label: String(minute).padStart(2, '0'),
status: slot ? slot.status : 'off-shift',
disabled: !slot || slot.status !== 'available'
}
})
const selectedMinuteIndex = Math.max(0, minuteValues.indexOf(selectedMinute))
return { timePickerMinutes: minutes, selectedMinuteIndex }
}
function customerCreatedAt(customer) {
return customer.createTime || customer.createdAt || customer.addedAt || ''
}
function formatCustomerCreatedAt(value) {
if (!value) return '添加时间未知'
return `添加于 ${String(value).replace('T', ' ').slice(0, 16)}`
}
function parseProductTags(product) {
if (Array.isArray(product.tagList) && product.tagList.length > 0) {
return product.tagList
}
if (Array.isArray(product.tagInfos) && product.tagInfos.length > 0) {
return product.tagInfos.map(item => item.tagName).filter(Boolean)
}
return String(product.tags || '')
.split(/[;,,、]/)
.map(item => item.trim())
.filter(Boolean)
}
function normalizeProduct(product, artists) {
const imageUrls = Array.isArray(product.imageUrls) ? product.imageUrls : []
const bookableArtists = String(product.bookableArtists || '')
.split(',')
.map(item => item.trim())
.filter(Boolean)
const artistNames = bookableArtists
.map(id => findArtist(artists, id).name)
.filter(Boolean)
const durationText = product.approximateDuration || (product.serviceDurationMinutes ? `${product.serviceDurationMinutes}分钟` : '')
return {
...product,
coverImage: imageUrls[0] || '',
tagList: parseProductTags(product).slice(0, 4),
artistText: artistNames.length > 0 ? artistNames.join('、') : '全部美甲师',
priceText: product.price || product.price === 0 ? `¥${product.price}` : '价格待定',
durationText
}
}
function isScheduleCoveringTime(schedule, form, startMinute, endMinute) {
if (!schedule || String(schedule.artistId) !== String(form.artistId) || schedule.date !== form.appointmentDate) {
return false
}
2026-06-27 16:12:00 +08:00
if (schedule.status !== 1 || Number(schedule.capacity === undefined ? 1 : schedule.capacity) < 1) {
return false
}
2026-06-27 16:12:00 +08:00
const scheduleStartMinute = dateUtil.minutesOfDay(extractTimeText(schedule.startTime))
const scheduleEndMinute = dateUtil.minutesOfDay(extractTimeText(schedule.endTime))
return scheduleStartMinute <= startMinute && scheduleEndMinute >= endMinute
}
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 || '客户',
2026-10-20 13:29:55 +08:00
displayPhone: phone || '未填写手机号',
createdAt: customerCreatedAt(customer)
2026-06-26 13:32:06 +08:00
}
}
function buildCustomerSelectorItem(customer) {
return {
...customer,
title: customer.displayName,
2026-10-20 13:29:55 +08:00
subtitle: formatCustomerCreatedAt(customer.createdAt),
rightText: customer.displayPhone
}
}
function buildArtistSelectorItem(artist) {
return {
...artist,
2026-10-20 18:02:49 +08:00
title: artist.name || '未命名美甲师',
subtitle: artist.statusText || '可用于指定预约',
meta: artist.workStartTime && artist.workEndTime ? `${artist.workStartTime.slice(0, 5)}-${artist.workEndTime.slice(0, 5)}` : '',
avatar: artist.avatar || artist.avatarUrl || '/assets/images/default-user-avatar.png'
}
}
2026-10-20 15:50:29 +08:00
function buildAppointmentDateLabels(value) {
const dateValue = String(value || dateUtil.formatDate(new Date()))
const date = new Date(dateValue.replace(/-/g, '/'))
if (Number.isNaN(date.getTime())) {
return { day: '', badge: dateValue, long: dateValue }
}
const today = dateUtil.formatDate(new Date())
const tomorrow = dateUtil.formatDate(dateUtil.addDays(new Date(), 1))
const dayLabel = dateValue === today
? '今天'
: dateValue === tomorrow
? '明天'
: `周${'日一二三四五六'[date.getDay()]}`
return {
day: dayLabel,
badge: `${dayLabel} · ${dateUtil.formatCnDate(dateValue)}`,
long: `${dayLabel} · ${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
}
}
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-10-20 13:29:55 +08:00
amount: '',
2026-06-04 16:39:06 +08:00
productId: '',
manualProductTitle: '',
manualProductPrice: '',
2026-06-27 15:19:32 +08:00
manualProductDescription: '',
manualProductTags: '',
manualProductTargetAudience: '',
manualProductPrecautions: '',
manualProductImageFileIds: '',
manualProductImageUrl: '',
2026-10-20 13:29:55 +08:00
durationMinutes: '60',
2026-06-04 16:39:06 +08:00
artistId: '',
2026-10-20 13:29:55 +08:00
createCustomerRecord: false,
2026-06-04 16:39:06 +08:00
remark: ''
},
2026-06-26 13:32:06 +08:00
customerOptions: [],
2026-10-20 13:29:55 +08:00
customerDirectory: [],
customerSheetVisible: false,
customerKeyword: '',
2026-10-20 13:29:55 +08:00
customerViewMode: 'list',
customerNewestFirst: true,
customerSuggestions: [],
2026-06-26 13:32:06 +08:00
customerLoading: false,
customerError: '',
2026-06-04 16:39:06 +08:00
products: [],
filteredProducts: [],
artists: [],
artistSelectorItems: [],
artistSheetVisible: false,
artistKeyword: '',
artistError: '',
2026-06-04 16:39:06 +08:00
selectedProduct: {},
selectedProductPriceText: '',
2026-06-04 16:39:06 +08:00
selectedArtist: {},
productModalVisible: false,
2026-10-20 15:50:29 +08:00
manualProductSheetVisible: false,
productKeyword: '',
2026-06-26 11:07:54 +08:00
productError: '',
loadingProducts: false,
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-06-27 16:12:00 +08:00
timeSheetVisible: false,
2026-10-20 13:29:55 +08:00
timePickerMode: 'wheel',
timePickerValue: [0, 0],
timePickerHours: [],
timePickerMinutes: [],
timePickerSlots: [],
timePickerGroups: [],
timePickerCandidateStatus: 'off-shift',
selectedTimeCandidate: '',
2026-06-27 16:12:00 +08:00
timeLoading: false,
timeError: '',
timeSelectTip: '请先选择美甲师并填写时长',
2026-10-20 15:50:29 +08:00
appointmentDayLabel: '',
appointmentDateBadge: '',
appointmentDateLong: '',
2026-06-27 16:12:00 +08:00
availableTimeGroups: [],
2026-06-04 16:39:06 +08:00
loading: false
},
onLoad(options) {
const creatable = canCreateAppointment()
2026-06-27 15:19:32 +08:00
const draftForm = creatable && !hasPresetOptions(options) ? readDraftForm() : null
const baseForm = draftForm || {}
2026-10-20 15:50:29 +08:00
const appointmentDate = options.date || baseForm.appointmentDate || dateUtil.formatDate(new Date())
const dateLabels = buildAppointmentDateLabels(appointmentDate)
2026-06-04 16:39:06 +08:00
this.setData({
canCreateAppointment: creatable,
2026-06-27 15:19:32 +08:00
form: {
...this.data.form,
...baseForm,
customerName: options.customerName ? decodeURIComponent(options.customerName) : (baseForm.customerName || ''),
phone: options.phone ? decodeURIComponent(options.phone) : (baseForm.phone || ''),
2026-10-20 15:50:29 +08:00
appointmentDate,
2026-06-27 15:19:32 +08:00
artistId: options.artistId || baseForm.artistId || ''
},
2026-10-20 15:50:29 +08:00
draftSavedAtText: draftForm ? '已恢复本机草稿' : '',
appointmentDayLabel: dateLabels.day,
appointmentDateBadge: dateLabels.badge,
appointmentDateLong: dateLabels.long
2026-06-04 16:39:06 +08:00
})
if (!creatable) {
2026-09-07 12:09:42 +08:00
wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' })
return
}
2026-06-04 16:39:06 +08:00
this.loadOptions()
},
async loadOptions() {
this.setData({ loadingProducts: true })
2026-06-04 16:39:06 +08:00
try {
const productsData = await productsApi.list({ page: 1, size: 100 })
2026-06-26 11:07:54 +08:00
const products = productsData.list || productsData || []
this.setData({ products, productError: '' })
2026-06-04 16:39:06 +08:00
} catch (error) {
2026-06-26 11:07:54 +08:00
this.setData({
products: [],
filteredProducts: [],
productError: error.message || '作品列表加载失败'
})
} finally {
this.setData({ loadingProducts: false })
2026-06-04 16:39:06 +08:00
}
await this.loadArtists()
this.refreshProductCards()
const selectedProduct = this.data.filteredProducts.find(item => String(item.id) === String(this.data.form.productId)) || {}
2026-10-20 13:29:55 +08:00
const selectedProductPatch = {
selectedProduct,
selectedProductPriceText: selectedProduct.priceText || ''
2026-10-20 13:29:55 +08:00
}
if (selectedProduct.id && (this.data.form.amount === '' || this.data.form.amount === undefined)) {
selectedProductPatch['form.amount'] = selectedProduct.price === undefined || selectedProduct.price === null ? '' : String(selectedProduct.price)
}
this.setData(selectedProductPatch)
2026-06-27 16:12:00 +08:00
await this.refreshAvailableTimes()
2026-06-04 16:39:06 +08:00
this.checkAvailability()
},
async loadArtists(preferredArtistId, fallbackEmployee) {
2026-06-26 11:07:54 +08:00
try {
const calendar = await planningApi.calendar({
startDate: this.data.form.appointmentDate,
endDate: this.data.form.appointmentDate
})
let artists = getCalendarArtists(calendar)
const requestedId = preferredArtistId || this.data.form.artistId
if (fallbackEmployee && requestedId && !findArtist(artists, requestedId).id) {
artists = artists.concat({
id: requestedId,
name: fallbackEmployee.name || fallbackEmployee.title,
avatar: fallbackEmployee.avatar || ''
})
}
const selectedArtist = requestedId ? findArtist(artists, requestedId) : {}
this.setData({
artists,
artistSelectorItems: this.filterArtistItems(artists, this.data.artistKeyword),
selectedArtist,
artistError: '',
'form.artistId': selectedArtist.id || ''
})
2026-06-26 11:07:54 +08:00
this.refreshProductCards()
} catch (error) {
this.setData({
artists: [],
artistSelectorItems: [],
2026-06-26 11:07:54 +08:00
selectedArtist: {},
'form.artistId': '',
2026-10-20 18:02:49 +08:00
artistError: error.message || '美甲师列表加载失败',
2026-06-26 11:07:54 +08:00
conflictTip: error.message || '美甲师列表加载失败',
conflictLevel: 'danger'
})
}
},
2026-10-20 13:29:55 +08:00
async loadCustomerDirectory() {
this.setData({ customerLoading: true })
try {
const size = 100
const rows = []
let page = 1
let total = Number.POSITIVE_INFINITY
while (rows.length < total) {
const result = await customersApi.list({ page, size })
const currentRows = Array.isArray(result) ? result : (result.list || [])
rows.push(...currentRows)
if (!Array.isArray(result) && Number.isFinite(Number(result.total))) {
total = Number(result.total)
} else if (currentRows.length < size) {
total = rows.length
}
if (currentRows.length === 0) break
page += 1
}
const directory = rows.map(normalizeCustomer)
this.setData({
customerDirectory: directory,
customerOptions: this.sortCustomerOptions(directory),
customerError: ''
})
this.refreshCustomerSuggestions(this.data.form.customerName, this.data.form.phone)
} catch (error) {
this.setData({ customerDirectory: [], customerOptions: [], customerError: error.message || '客户列表加载失败' })
} finally {
this.setData({ customerLoading: false })
}
},
sortCustomerOptions(customers, newestFirst = this.data.customerNewestFirst) {
return (customers || []).slice().sort((left, right) => {
const leftDate = String(left.createdAt || '')
const rightDate = String(right.createdAt || '')
return newestFirst ? rightDate.localeCompare(leftDate) : leftDate.localeCompare(rightDate)
}).map(buildCustomerSelectorItem)
},
2026-06-04 16:39:06 +08:00
onInput(event) {
2026-06-26 13:32:06 +08:00
const field = event.currentTarget.dataset.field
const patch = {
[`form.${field}`]: event.detail.value
}
this.setData(patch)
2026-06-27 16:12:00 +08:00
if (field === 'durationMinutes') {
this.refreshAvailableTimes()
this.checkAvailability()
}
2026-06-26 13:32:06 +08:00
},
2026-10-20 13:29:55 +08:00
onStyleTitleInput(event) {
const patch = { 'form.manualProductTitle': event.detail.value }
if (this.data.form.productId) {
patch['form.productId'] = ''
patch.selectedProduct = {}
patch.selectedProductPriceText = ''
patch['form.manualProductImageFileIds'] = ''
patch['form.manualProductImageUrl'] = ''
}
this.setData(patch)
},
2026-10-16 17:33:58 +08:00
onCustomerInput(event) {
const field = event.currentTarget.dataset.field
const patch = {
[`form.${field}`]: event.detail.value,
2026-10-20 13:29:55 +08:00
'form.customerUserId': '',
'form.createCustomerRecord': false
2026-10-16 17:33:58 +08:00
}
this.setData({
...patch
})
2026-10-20 13:29:55 +08:00
const customerName = field === 'customerName' ? event.detail.value : this.data.form.customerName
const phone = field === 'phone' ? event.detail.value : this.data.form.phone
this.refreshCustomerSuggestions(customerName, phone)
},
refreshCustomerSuggestions(nameValue, phoneValue) {
const name = String(nameValue || '').trim().toLowerCase()
const phone = String(phoneValue || '').trim().toLowerCase()
if (!name && !phone) {
this._customerSuggestionSeq = (this._customerSuggestionSeq || 0) + 1
clearTimeout(this._suggestionTimer)
this.setData({ customerSuggestions: [] })
return
}
const suggestions = this.data.customerDirectory
.filter(customer => (!name || customer.name.toLowerCase().includes(name)) && (!phone || customer.phone.toLowerCase().includes(phone)))
.slice(0, 3)
.map(buildCustomerSelectorItem)
this.setData({ customerSuggestions: suggestions })
const requestSeq = (this._customerSuggestionSeq || 0) + 1
this._customerSuggestionSeq = requestSeq
clearTimeout(this._suggestionTimer)
this._suggestionTimer = setTimeout(async () => {
try {
const result = await customersApi.list({ page: 1, size: 50, keyword: name || phone })
if (requestSeq !== this._customerSuggestionSeq) return
const rows = Array.isArray(result) ? result : (result.list || [])
const remoteSuggestions = rows.map(normalizeCustomer)
.filter(customer => (!name || customer.name.toLowerCase().includes(name)) && (!phone || customer.phone.toLowerCase().includes(phone)))
.slice(0, 3)
.map(buildCustomerSelectorItem)
this.setData({ customerSuggestions: remoteSuggestions })
} catch (error) {
if (requestSeq === this._customerSuggestionSeq && suggestions.length === 0) {
this.setData({ customerSuggestions: [] })
}
}
}, 240)
},
selectCustomerSuggestion(event) {
const index = Number(event.currentTarget.dataset.index)
const customer = this.data.customerSuggestions[index]
if (!customer) return
this.setData({
'form.customerUserId': customer.id,
'form.customerName': customer.name,
'form.phone': customer.phone,
'form.createCustomerRecord': false,
customerSuggestions: [],
customerSheetVisible: false,
customerKeyword: ''
})
2026-10-16 17:33:58 +08:00
},
openCustomerSheet() {
this.setData({ customerSheetVisible: true })
this.searchCustomers(this.data.customerKeyword)
2026-06-26 13:32:06 +08:00
},
closeCustomerSheet() {
this.setData({ customerSheetVisible: false })
},
onCustomerSearch(event) {
const keyword = event.detail.value
this.setData({ customerKeyword: keyword })
2026-06-26 13:32:06 +08:00
clearTimeout(this._customerTimer)
this._customerTimer = setTimeout(() => this.searchCustomers(keyword), 250)
2026-06-26 13:32:06 +08:00
},
async searchCustomers(keywordValue) {
2026-06-26 13:32:06 +08:00
if (!this.data.canCreateAppointment) {
return
}
const keyword = String(keywordValue === undefined ? this.data.customerKeyword : keywordValue || '').trim()
2026-10-20 13:29:55 +08:00
if (this.data.customerDirectory.length === 0) await this.loadCustomerDirectory()
const matches = this.data.customerDirectory.filter(customer =>
!keyword || `${customer.name} ${customer.phone}`.toLowerCase().includes(keyword.toLowerCase())
)
this.setData({ customerOptions: this.sortCustomerOptions(matches), customerError: '' })
},
changeCustomerView(event) {
this.setData({ customerViewMode: event.detail.mode || 'list' })
},
toggleCustomerSort() {
const customerNewestFirst = !this.data.customerNewestFirst
const keyword = String(this.data.customerKeyword || '').trim().toLowerCase()
const matches = this.data.customerDirectory.filter(customer =>
!keyword || `${customer.name} ${customer.phone}`.toLowerCase().includes(keyword)
)
this.setData({ customerNewestFirst, customerOptions: this.sortCustomerOptions(matches, customerNewestFirst) })
2026-06-26 13:32:06 +08:00
},
retryCustomerSearch() {
this.searchCustomers(this.data.customerKeyword)
},
2026-06-26 13:32:06 +08:00
selectCustomer(event) {
const customer = event.detail.item
2026-06-26 13:32:06 +08:00
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,
2026-10-20 13:29:55 +08:00
'form.createCustomerRecord': false,
customerSheetVisible: false,
2026-10-20 13:29:55 +08:00
customerKeyword: '',
customerSuggestions: []
2026-06-04 16:39:06 +08:00
})
},
2026-06-26 13:32:06 +08:00
onUnload() {
if (this._customerTimer) {
clearTimeout(this._customerTimer)
}
2026-10-20 13:29:55 +08:00
if (this._suggestionTimer) {
clearTimeout(this._suggestionTimer)
}
2026-06-26 13:32:06 +08:00
},
async onDateChange(event) {
const nextDate = event.detail.value
const today = dateUtil.formatDate(new Date())
if (nextDate < today) {
const result = await new Promise(resolve => {
wx.showModal({
title: '历史日期不能新建预约',
2026-10-20 18:02:49 +08:00
content: '之前的日期只能作为历史补单记录,不会校验美甲师排班,也不会占用预约时段。',
cancelText: '取消',
confirmText: '去补单',
success: resolve,
fail: () => resolve({ confirm: false })
})
})
if (result.confirm) {
const query = [`serviceDate=${encodeURIComponent(nextDate)}`]
if (this.data.form.artistId) {
query.push(`artistId=${encodeURIComponent(this.data.form.artistId)}`)
}
wx.navigateTo({ url: `/pages/backfill-order/index?${query.join('&')}` })
}
return
}
2026-10-20 15:50:29 +08:00
const dateLabels = buildAppointmentDateLabels(nextDate)
2026-06-27 16:12:00 +08:00
this.setData({
'form.appointmentDate': nextDate,
2026-10-20 15:50:29 +08:00
'form.appointmentTime': '',
appointmentDayLabel: dateLabels.day,
appointmentDateBadge: dateLabels.badge,
appointmentDateLong: dateLabels.long
2026-06-27 16:12:00 +08:00
})
await this.loadArtists()
2026-06-27 16:12:00 +08:00
await this.refreshAvailableTimes()
2026-06-04 16:39:06 +08:00
this.checkAvailability()
},
refreshProductCards() {
const keyword = this.data.productKeyword.trim().toLowerCase()
const products = this.data.products
.map(product => normalizeProduct(product, this.data.artists))
.filter(product => {
if (!keyword) return true
return [product.title, product.artistText, product.priceText, product.durationText, ...(product.tagList || [])]
.some(value => String(value || '').toLowerCase().includes(keyword))
})
this.setData({ filteredProducts: products })
},
openProductModal() {
this.refreshProductCards()
2026-10-20 15:50:29 +08:00
this.setData({ productModalVisible: true, manualProductSheetVisible: false })
},
closeProductModal() {
2026-10-20 13:29:55 +08:00
this.setData({ productModalVisible: false })
},
openManualProduct() {
2026-10-20 13:29:55 +08:00
this.setData({
productModalVisible: false,
2026-10-20 15:50:29 +08:00
manualProductSheetVisible: true
})
},
closeManualProduct() {
this.setData({ manualProductSheetVisible: false })
},
confirmManualProduct() {
const hasTitle = Boolean(String(this.data.form.manualProductTitle || '').trim())
const hasImage = Boolean(String(this.data.form.manualProductImageFileIds || '').trim())
const hasFallbackName = Boolean(String(this.data.form.customerName || '').trim())
if (this.data.form.productId && !hasTitle && !hasImage) {
this.closeManualProduct()
return
}
if (!hasTitle && !hasImage && !hasFallbackName) {
wx.showToast({ title: '请填写款式名称或添加图片', icon: 'none' })
return
}
this.setData({
'form.productId': '',
2026-10-20 13:29:55 +08:00
selectedProduct: {},
selectedProductPriceText: '',
2026-10-20 15:50:29 +08:00
manualProductSheetVisible: false
2026-10-20 13:29:55 +08:00
})
},
stopTap() {
},
2026-10-12 17:37:51 +08:00
stopTouchMove() {
},
onProductSearch(event) {
this.setData({ productKeyword: event.detail.value })
this.refreshProductCards()
},
selectProduct(event) {
const selectedProduct = event.detail.item || this.data.filteredProducts.find(item => String(item.id) === String(event.currentTarget.dataset.id)) || {}
const selectedDuration = parseInt(selectedProduct.serviceDurationMinutes || selectedProduct.approximateDuration, 10)
2026-06-04 16:39:06 +08:00
this.setData({
selectedProduct,
selectedProductPriceText: selectedProduct.priceText || '',
2026-06-04 16:39:06 +08:00
'form.productId': selectedProduct.id,
2026-10-20 15:50:29 +08:00
'form.manualProductTitle': '',
'form.manualProductPrice': '',
'form.manualProductDescription': '',
'form.manualProductTags': '',
'form.manualProductTargetAudience': '',
'form.manualProductPrecautions': '',
'form.manualProductImageFileIds': '',
'form.manualProductImageUrl': '',
2026-10-20 13:29:55 +08:00
'form.amount': selectedProduct.price === undefined || selectedProduct.price === null ? '' : String(selectedProduct.price),
'form.durationMinutes': String(selectedDuration || this.data.form.durationMinutes || '')
2026-06-04 16:39:06 +08:00
})
this.closeProductModal()
2026-06-27 16:12:00 +08:00
this.refreshAvailableTimes()
this.checkAvailability()
},
2026-06-27 15:19:32 +08:00
async chooseManualProductImage() {
if (this.data.manualImageUploading) {
return
}
try {
const filePath = await chooseImageFilePath()
if (!filePath) {
return
}
this.setData({ manualImageUploading: true })
const uploadResult = await uploadObjectFile(filePath)
const fileId = uploadResult.id || uploadResult.fileId
const fileUrl = uploadResult.fileUrl || uploadResult.primaryUrl || filePath
if (!fileId) {
throw new Error('作品图片上传成功但未返回文件ID')
}
this.setData({
2026-10-20 13:29:55 +08:00
'form.productId': '',
selectedProduct: {},
selectedProductPriceText: '',
'form.manualProductImageFileIds': String(fileId),
'form.manualProductImageUrl': fileUrl
2026-06-27 15:19:32 +08:00
})
} catch (error) {
wx.showToast({ title: error.message || '图片上传失败', icon: 'none' })
} finally {
this.setData({ manualImageUploading: false })
}
},
removeManualProductImage() {
this.setData({
2026-10-20 13:29:55 +08:00
'form.manualProductImageFileIds': '',
'form.manualProductImageUrl': ''
2026-06-27 15:19:32 +08:00
})
},
filterArtistItems(artists, keywordValue) {
const keyword = String(keywordValue || '').trim().toLowerCase()
const items = (artists || [])
.filter(item => !keyword || String(item.name || '').toLowerCase().includes(keyword))
.map(buildArtistSelectorItem)
if (!keyword || '暂不分配'.includes(keyword)) {
2026-10-20 18:02:49 +08:00
items.unshift({ id: '__unassigned__', title: '暂不分配', subtitle: '先记录预约,后续再分配美甲师', badge: '待分配' })
}
return items
},
openArtistSheet() {
this.setData({
artistSheetVisible: true,
artistSelectorItems: this.filterArtistItems(this.data.artists, this.data.artistKeyword)
})
},
closeArtistSheet() {
this.setData({ artistSheetVisible: false })
},
retryArtists() {
this.loadArtists()
},
onArtistSearch(event) {
const artistKeyword = event.detail.value
this.setData({
artistKeyword,
artistSelectorItems: this.filterArtistItems(this.data.artists, artistKeyword)
})
},
selectArtist(event) {
const selectedArtist = event.detail.item || {}
if (selectedArtist.id === '__unassigned__') {
this.setData({
selectedArtist: {},
'form.artistId': '',
artistSheetVisible: false,
conflictTip: '',
conflictLevel: 'free'
})
this.refreshAvailableTimes()
return
}
2026-06-04 16:39:06 +08:00
this.setData({
selectedArtist,
2026-06-27 16:12:00 +08:00
'form.artistId': selectedArtist.id,
'form.appointmentTime': '',
artistSheetVisible: false
2026-06-27 16:12:00 +08:00
})
this.refreshAvailableTimes()
this.checkAvailability()
},
addEmployeeFromSelector() {
this.setData({ artistSheetVisible: false })
wx.navigateTo({
url: `/pages/employee-create/index?picker=1&date=${encodeURIComponent(this.data.form.appointmentDate || '')}&time=${encodeURIComponent(this.data.form.appointmentTime || '')}&durationMinutes=${encodeURIComponent(this.data.form.durationMinutes || '')}`,
success: result => {
result.eventChannel.on('employeeCreated', employee => this.handleEmployeeCreated(employee))
}
})
},
async handleEmployeeCreated(employee) {
const originalTime = this.data.form.appointmentTime
await this.loadArtists(employee.autoSelect === false ? '' : employee.id, employee)
if (employee.autoSelect === false) {
this.setData({ selectedArtist: {}, 'form.artistId': '' })
await this.refreshAvailableTimes()
return
}
if (employee.scheduleSaved && originalTime) {
const availability = await this.checkAvailability()
if (!availability.ok) {
this.setData({
selectedArtist: {},
'form.artistId': '',
'form.appointmentTime': originalTime,
2026-10-20 18:02:49 +08:00
conflictTip: `${availability.tip || '新美甲师当前排班无法承接'},预约已保持待分配`,
conflictLevel: 'danger'
})
}
} else {
this.setData({ 'form.appointmentTime': '' })
}
await this.refreshAvailableTimes()
if (this.data.form.artistId) this.checkAvailability()
},
2026-06-27 16:12:00 +08:00
canOpenTimeSheet() {
const form = this.data.form
return Boolean(form.appointmentDate && normalizeDuration(form.durationMinutes))
2026-06-27 16:12:00 +08:00
},
async refreshAvailableTimes() {
const form = this.data.form
const durationMinutes = normalizeDuration(form.durationMinutes)
const requestSeq = (this._availableTimeRequestSeq || 0) + 1
this._availableTimeRequestSeq = requestSeq
if (!form.appointmentDate || !durationMinutes) {
2026-06-27 16:12:00 +08:00
const patch = {
availableTimeGroups: [],
2026-10-20 13:29:55 +08:00
timePickerGroups: [],
timePickerSlots: [],
timePickerHours: [],
timePickerMinutes: [],
timePickerValue: [0, 0],
selectedTimeCandidate: '',
timePickerCandidateStatus: 'off-shift',
2026-06-27 16:12:00 +08:00
timeError: '',
timeSelectTip: '请先填写预约日期和时长'
2026-06-27 16:12:00 +08:00
}
if (form.appointmentTime) {
patch['form.appointmentTime'] = ''
}
this.setData(patch)
return
}
if (!form.artistId) {
const availableTimeGroups = buildUnassignedTimeGroups(durationMinutes)
2026-10-20 13:29:55 +08:00
const timePickerSlots = buildTimePickerSlots({ schedules: [], appointments: [] }, form, durationMinutes)
this.setData({
availableTimeGroups,
2026-10-20 13:29:55 +08:00
timePickerSlots,
timePickerGroups: buildTimePickerGroups(timePickerSlots),
...buildTimeWheelState(timePickerSlots, form.appointmentTime),
timeError: '',
timeLoading: false,
2026-10-20 18:02:49 +08:00
timeSelectTip: '请选择预约时间,美甲师可稍后分配'
})
return
}
2026-06-27 16:12:00 +08:00
this.setData({
timeLoading: true,
timeError: '',
timeSelectTip: '正在计算可约时间...'
})
try {
const calendar = await planningApi.calendar({
startDate: form.appointmentDate,
endDate: form.appointmentDate,
artistId: form.artistId
})
if (requestSeq !== this._availableTimeRequestSeq) {
return
}
const availableTimeGroups = buildAvailableTimeGroups(calendar, form, durationMinutes)
const availableTimes = flattenTimeGroups(availableTimeGroups).map(item => item.value)
2026-10-20 13:29:55 +08:00
const timePickerSlots = buildTimePickerSlots(calendar, form, durationMinutes)
2026-06-27 16:12:00 +08:00
const patch = {
availableTimeGroups,
2026-10-20 13:29:55 +08:00
timePickerSlots,
timePickerGroups: buildTimePickerGroups(timePickerSlots),
...buildTimeWheelState(timePickerSlots, form.appointmentTime),
2026-06-27 16:12:00 +08:00
timeSelectTip: availableTimes.length > 0 ? '请选择预约时间' : '当前美甲师当天暂无可约时间'
}
if (form.appointmentTime && !availableTimes.includes(form.appointmentTime)) {
patch['form.appointmentTime'] = ''
}
this.setData(patch)
} catch (error) {
if (requestSeq !== this._availableTimeRequestSeq) {
return
}
this.setData({
availableTimeGroups: [],
timeError: error.message || '可约时间加载失败',
timeSelectTip: '可约时间加载失败'
})
} finally {
if (requestSeq === this._availableTimeRequestSeq) {
this.setData({ timeLoading: false })
}
}
},
async openTimeSheet() {
if (!this.canOpenTimeSheet()) {
wx.showToast({ title: '请先填写预约日期和时长', icon: 'none' })
2026-06-27 16:12:00 +08:00
return
}
2026-10-20 13:29:55 +08:00
this.setData({ timeSheetVisible: true, timePickerMode: 'wheel' })
2026-06-27 16:12:00 +08:00
await this.refreshAvailableTimes()
},
closeTimeSheet() {
this.setData({ timeSheetVisible: false })
},
selectAvailableTime(event) {
const value = event.currentTarget.dataset.value
2026-10-20 13:29:55 +08:00
const slot = this.data.timePickerSlots.find(item => item.value === value)
if (!slot || slot.status !== 'available') {
wx.showToast({ title: slot && slot.status === 'occupied' ? '该时间已被占用' : '该时间不可预约', icon: 'none' })
return
}
this.setData({ selectedTimeCandidate: value, timePickerCandidateStatus: slot.status })
2026-06-04 16:39:06 +08:00
},
2026-10-20 13:29:55 +08:00
onTimePickerModeChange(event) {
this.setData({ timePickerMode: event.currentTarget.dataset.mode || 'wheel' })
},
onTimePickerChange(event) {
const values = event.detail.value || [0, 0]
const hourItem = this.data.timePickerHours[values[0]]
if (!hourItem) return
const hour = Number(hourItem.value)
const minuteIndex = Number(values[1] || 0)
const minuteItem = this.data.timePickerMinutes[minuteIndex]
const minute = minuteItem ? Number(minuteItem.value) : 0
const candidate = `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`
const slot = this.data.timePickerSlots.find(item => item.value === candidate)
const nextMinutes = timeWheelStateForHour(this.data.timePickerSlots, hour, minute)
this.setData({
timePickerValue: [Number(values[0]), nextMinutes.selectedMinuteIndex],
timePickerMinutes: nextMinutes.timePickerMinutes,
selectedTimeCandidate: candidate,
timePickerCandidateStatus: slot ? slot.status : 'off-shift'
})
},
confirmTimeSelection() {
const candidate = this.data.selectedTimeCandidate
const slot = this.data.timePickerSlots.find(item => item.value === candidate)
if (!slot || slot.status !== 'available') {
wx.showToast({ title: slot && slot.status === 'occupied' ? '该时间已被占用' : '该时间不可预约', icon: 'none' })
return
}
this.checkAvailability(candidate).then(availability => {
if (!availability.ok) {
wx.showToast({
title: availability.tip && availability.tip.includes('已有预约') ? '该时间已被占用' : availability.tip || '该时间不可预约',
icon: 'none'
})
return
}
this.setData({ 'form.appointmentTime': candidate, timeSheetVisible: false })
this.checkAvailability()
})
},
async checkAvailability(candidateTime) {
2026-06-04 16:39:06 +08:00
const form = this.data.form
2026-10-20 13:29:55 +08:00
const appointmentTime = candidateTime || form.appointmentTime
if (!form.appointmentDate || !appointmentTime) {
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-10-20 13:29:55 +08:00
const startMinute = dateUtil.minutesOfDay(appointmentTime)
2026-06-04 16:39:06 +08:00
const endMinute = startMinute + durationMinutes
if (startMinute < dateUtil.minutesOfDay('10:00') || endMinute > dateUtil.minutesOfDay('22:00')) {
const tip = '该时间超出营业时间 10:00-22:00'
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
return { ok: false, tip }
}
if (!form.artistId) {
2026-10-20 18:02:49 +08:00
const tip = '预约将保存为待分配,当前不会占用美甲师时间'
this.setData({ conflictTip: tip, conflictLevel: 'free' })
return { ok: true, tip }
}
2026-06-04 16:39:06 +08:00
try {
const calendar = await planningApi.calendar({
startDate: form.appointmentDate,
endDate: form.appointmentDate,
artistId: form.artistId
})
const schedule = (calendar.schedules || []).find(item => isScheduleCoveringTime(item, form, startMinute, endMinute))
if (!schedule) {
const tip = `${this.data.selectedArtist.name || '该美甲师'} 当前时段无可预约排班`
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
return { ok: false, tip }
2026-06-04 16:39:06 +08:00
}
const conflicts = (calendar.appointments || []).filter(item => {
2026-06-27 16:12:00 +08:00
if (String(item.artistId) !== String(form.artistId) || normalizeAppointmentDate(item) !== form.appointmentDate) return false
if (isCancelledAppointment(item)) return false
const itemStart = resolveAppointmentStartMinute(item)
const itemEnd = resolveAppointmentEndMinute(item, itemStart)
2026-06-04 16:39:06 +08:00
return startMinute < itemEnd && endMinute > itemStart
})
if (conflicts.length > 0) {
const first = conflicts[0]
2026-06-27 16:12:00 +08:00
const itemStart = resolveAppointmentStartMinute(first)
const itemEnd = resolveAppointmentEndMinute(first, itemStart)
2026-06-04 16:39:06 +08:00
const tip = `${this.data.selectedArtist.name || '该美甲师'} ${dateUtil.timeFromMinutes(itemStart)}-${dateUtil.timeFromMinutes(itemEnd)} 已有预约`
this.setData({ conflictTip: tip, conflictLevel: 'danger' })
return { ok: false, tip }
}
2026-10-20 13:29:55 +08:00
const tip = `${this.data.selectedArtist.name || '该美甲师'} ${appointmentTime}-${dateUtil.timeFromMinutes(endMinute)} 可预约`
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
}
},
2026-10-16 17:33:58 +08:00
async ensureCustomerBeforeSubmit() {
const name = String(this.data.form.customerName || '').trim()
const phone = String(this.data.form.phone || '').trim()
2026-10-20 13:29:55 +08:00
if (!name && !phone) {
this.setData({ 'form.createCustomerRecord': false })
return true
}
2026-10-16 17:33:58 +08:00
if (!name) {
2026-10-20 13:29:55 +08:00
wx.showToast({ title: '填写手机号时请同时填写客户姓名', icon: 'none' })
2026-10-16 17:33:58 +08:00
return false
}
if (phone && !/^1[3-9]\d{9}$/.test(phone)) {
wx.showToast({ title: '请输入正确手机号', icon: 'none' })
return false
}
if (this.data.form.customerUserId) {
2026-10-20 13:29:55 +08:00
this.setData({ 'form.createCustomerRecord': false })
2026-10-16 17:33:58 +08:00
return true
}
this.setData({ loading: true })
try {
const matches = await customersApi.matchIdentity(name, phone || undefined)
if (matches.length > 1) {
2026-10-20 13:29:55 +08:00
const choice = await new Promise(resolve => {
wx.showModal({
title: '找到多个同名客户',
content: phone ? '无法确定唯一客户,请选择已有客户或按散客继续。' : '请先补充手机号或选择一个已有客户,也可以按散客继续。',
cancelText: '不关联提交',
confirmText: '选择客户',
success: resolve,
fail: () => resolve({ confirm: false })
})
})
if (!choice.confirm) {
this.setData({ 'form.createCustomerRecord': false })
return true
}
2026-10-16 17:33:58 +08:00
this.setData({
customerOptions: matches.map(normalizeCustomer).map(buildCustomerSelectorItem),
customerKeyword: name,
customerSheetVisible: true
})
return false
}
if (matches.length > 0) {
const customer = normalizeCustomer(matches[0])
const choice = await new Promise(resolve => {
wx.showModal({
title: '客户已存在',
content: `系统中已有“${name}”${phone ? `(${phone})` : ''},是否使用该客户?`,
2026-10-20 13:29:55 +08:00
cancelText: '不关联提交',
2026-10-16 17:33:58 +08:00
confirmText: '使用已有',
success: resolve,
fail: () => resolve({ confirm: false })
})
})
2026-10-20 13:29:55 +08:00
if (choice.confirm) {
this.setData({
'form.customerUserId': customer.id,
'form.customerName': customer.name,
'form.phone': customer.phone,
'form.createCustomerRecord': false
})
} else {
this.setData({ 'form.createCustomerRecord': false })
2026-10-16 17:33:58 +08:00
}
return true
}
const createChoice = await new Promise(resolve => {
wx.showModal({
title: '新建客户',
content: '系统中没有匹配客户,是否新建到客户档案?',
cancelText: '不新建',
confirmText: '确认',
success: resolve,
fail: () => resolve({ confirm: false })
})
})
2026-10-20 13:29:55 +08:00
this.setData({ 'form.createCustomerRecord': Boolean(createChoice.confirm) })
2026-10-16 17:33:58 +08:00
return true
} catch (error) {
wx.showToast({ title: error.message || '客户校验失败,请稍后重试', icon: 'none' })
return false
} finally {
this.setData({ loading: false })
}
},
2026-06-04 16:39:06 +08:00
async submit() {
2026-10-16 17:33:58 +08:00
if (this.data.loading) {
return
}
if (!this.data.canCreateAppointment) {
2026-09-07 12:09:42 +08:00
wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' })
return
}
2026-10-20 13:29:55 +08:00
let form = this.data.form
const manualProductTitle = String(form.manualProductTitle || '').trim()
const manualProductImageFileIds = String(form.manualProductImageFileIds || '').trim()
const hasManualProduct = Boolean(manualProductTitle || manualProductImageFileIds || String(form.customerName || '').trim())
const amountText = String(form.amount === undefined || form.amount === null ? '' : form.amount).trim()
const amount = Number(amountText)
2026-06-27 15:19:32 +08:00
const durationMinutes = normalizeDuration(form.durationMinutes)
2026-10-20 13:29:55 +08:00
if ((!form.productId && !hasManualProduct) || !form.appointmentDate || !form.appointmentTime || !amountText) {
2026-06-04 16:39:06 +08:00
wx.showToast({ title: '请补全预约信息', icon: 'none' })
return
}
2026-10-20 13:29:55 +08:00
if (!Number.isFinite(amount) || amount < 0) {
wx.showToast({ title: '请输入不小于0的成交金额', icon: 'none' })
return
}
if (form.phone && !String(form.customerName || '').trim()) {
wx.showToast({ title: '填写手机号时请同时填写客户姓名', icon: 'none' })
return
}
2026-10-16 17:33:58 +08:00
if (form.phone && !/^1[3-9]\d{9}$/.test(String(form.phone).trim())) {
wx.showToast({ title: '请输入正确手机号', icon: 'none' })
return
}
2026-06-27 15:19:32 +08:00
if (!durationMinutes) {
wx.showToast({ title: '请填写预约时长', icon: 'none' })
return
}
2026-06-04 16:39:06 +08:00
const availability = await this.checkAvailability()
if (!availability.ok) {
wx.showToast({ title: availability.tip || '该时段已被预约', icon: 'none' })
return
}
if (!form.artistId) {
const result = await new Promise(resolve => {
wx.showModal({
title: '保存为待分配预约',
2026-10-20 18:02:49 +08:00
content: '当前未指定美甲师,预约会正常保存,但不会占用美甲师时间。可以稍后在预约详情中分配。',
cancelText: '返回选择',
confirmText: '继续保存',
success: resolve,
fail: () => resolve({ confirm: false })
})
})
if (!result.confirm) return
}
2026-10-16 17:33:58 +08:00
if (!(await this.ensureCustomerBeforeSubmit())) {
return
}
2026-10-20 13:29:55 +08:00
form = this.data.form
2026-06-04 16:39:06 +08:00
this.setData({ loading: true })
try {
const payload = {
2026-06-04 16:39:06 +08:00
...form,
2026-06-26 13:32:06 +08:00
customerUserId: form.customerUserId ? String(form.customerUserId) : undefined,
artistId: form.artistId ? String(form.artistId) : undefined,
2026-10-20 13:29:55 +08:00
customerName: String(form.customerName || '').trim() || undefined,
phone: String(form.phone || '').trim() || undefined,
amount,
createCustomerRecord: Boolean(form.createCustomerRecord),
2026-06-27 15:19:32 +08:00
durationMinutes,
clientRequestId: buildClientRequestId('manager-appointment')
}
if (form.productId) {
payload.productId = String(form.productId)
payload.manualProductTitle = undefined
payload.manualProductPrice = undefined
} else {
payload.productId = undefined
2026-10-20 13:29:55 +08:00
payload.manualProductTitle = manualProductTitle || undefined
payload.manualProductPrice = amount
2026-06-27 15:19:32 +08:00
payload.manualProductDescription = String(form.manualProductDescription || '').trim() || undefined
payload.manualProductTags = String(form.manualProductTags || '').trim() || undefined
payload.manualProductTargetAudience = String(form.manualProductTargetAudience || '').trim() || undefined
payload.manualProductPrecautions = String(form.manualProductPrecautions || '').trim() || undefined
payload.manualProductImageFileIds = String(form.manualProductImageFileIds || '').trim() || undefined
}
const result = await planningApi.createAppointment(payload)
2026-06-27 15:19:32 +08:00
removeDraftForm()
2026-06-27 02:52:47 +08:00
markPlanningRefresh()
2026-06-04 16:39:06 +08:00
wx.redirectTo({ url: `/pages/appointment-detail/index?id=${result.orderItemId}` })
} catch (error) {
2026-06-27 15:19:32 +08:00
wx.showToast({ title: error.message || '提交失败', icon: 'none' })
2026-06-04 16:39:06 +08:00
} finally {
this.setData({ loading: false })
}
},
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' })
}
},
clearDraft() {
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()
}
})