const planningApi = require('../../api/planning') const productsApi = require('../../api/products') const customersApi = require('../../api/customers') const dateUtil = require('../../utils/date') const { markPlanningRefresh } = require('../../utils/planning-refresh') function buildClientRequestId(prefix) { return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}` } function getCalendarArtists(calendar) { return calendar && Array.isArray(calendar.artists) ? calendar.artists : [] } function findArtist(artists, artistId) { return artists.find(item => String(item.id) === String(artistId)) || {} } function canCreateAppointment() { const app = getApp() const userInfo = app.globalData.userInfo || {} return Number(userInfo.type) !== 3 } function parseProductTags(product) { if (Array.isArray(product.tagList) && product.tagList.length > 0) { return product.tagList } if (Array.isArray(product.tagInfos) && product.tagInfos.length > 0) { return product.tagInfos.map(item => item.tagName).filter(Boolean) } return String(product.tags || '') .split(/[;,,、]/) .map(item => item.trim()) .filter(Boolean) } function normalizeProduct(product, artists) { const imageUrls = Array.isArray(product.imageUrls) ? product.imageUrls : [] const bookableArtists = String(product.bookableArtists || '') .split(',') .map(item => item.trim()) .filter(Boolean) const artistNames = bookableArtists .map(id => findArtist(artists, id).name) .filter(Boolean) const durationText = product.approximateDuration || (product.serviceDurationMinutes ? `${product.serviceDurationMinutes}分钟` : '') return { ...product, coverImage: imageUrls[0] || '', tagList: parseProductTags(product).slice(0, 4), artistText: artistNames.length > 0 ? artistNames.join('、') : '全部美甲师', priceText: product.price || product.price === 0 ? `¥${product.price}` : '价格待定', durationText } } function isScheduleCoveringTime(schedule, form, startMinute, endMinute) { if (!schedule || String(schedule.artistId) !== String(form.artistId) || schedule.date !== form.appointmentDate) { return false } if (schedule.status !== 1 || Number(schedule.capacity || 0) < 1) { return false } const scheduleStartMinute = dateUtil.minutesOfDay(String(schedule.startTime || '').slice(0, 5)) const scheduleEndMinute = dateUtil.minutesOfDay(String(schedule.endTime || '').slice(0, 5)) return scheduleStartMinute <= startMinute && scheduleEndMinute >= endMinute } function normalizeCustomer(customer) { const name = customer.nickname || customer.name || customer.account || '' const phone = customer.contactPhone || customer.phone || '' return { id: customer.id, name, phone, displayName: name || phone || '客户', displayPhone: phone || '未填写手机号' } } Page({ data: { form: { customerUserId: '', customerName: '', phone: '', appointmentDate: dateUtil.formatDate(new Date()), appointmentTime: '13:00', productId: '', manualProductTitle: '', manualProductPrice: '', durationMinutes: '', artistId: '', remark: '' }, customerOptions: [], customerDropdownVisible: false, customerLoading: false, customerError: '', products: [], filteredProducts: [], artists: [], selectedProduct: {}, selectedArtist: {}, productModalVisible: false, productKeyword: '', productError: '', conflictTip: '', conflictLevel: 'free', canCreateAppointment: true, loading: false }, onLoad(options) { const creatable = canCreateAppointment() this.setData({ canCreateAppointment: creatable, 'form.customerName': options.customerName ? decodeURIComponent(options.customerName) : '', 'form.phone': options.phone ? decodeURIComponent(options.phone) : '', 'form.appointmentDate': options.date || dateUtil.formatDate(new Date()), 'form.artistId': options.artistId || '' }) if (!creatable) { wx.showToast({ title: '美甲师账号只能查看预约', icon: 'none' }) return } this.loadOptions() this.searchCustomers() }, 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.loadArtists() this.refreshProductCards() this.checkAvailability() }, 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 patch = { [`form.${field}`]: event.detail.value } if (field === 'customerName' || field === 'phone') { patch['form.customerUserId'] = '' patch.customerDropdownVisible = true } this.setData(patch) if (field === 'customerName' || field === 'phone') { this.scheduleCustomerSearch(field) } }, onCustomerFocus(event) { const field = event.currentTarget.dataset.field this.setData({ customerDropdownVisible: true }) 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 }) }, 180) }, onUnload() { if (this._customerTimer) { clearTimeout(this._customerTimer) } }, async onDateChange(event) { this.setData({ 'form.appointmentDate': event.detail.value }) await this.loadArtists() this.checkAvailability() }, onTimeChange(event) { this.setData({ 'form.appointmentTime': event.detail.value }) this.checkAvailability() }, refreshProductCards() { const keyword = this.data.productKeyword.trim().toLowerCase() const products = this.data.products .map(product => normalizeProduct(product, this.data.artists)) .filter(product => { if (!keyword) return true return [product.title, product.artistText, product.priceText, product.durationText, ...(product.tagList || [])] .some(value => String(value || '').toLowerCase().includes(keyword)) }) this.setData({ filteredProducts: products }) }, openProductModal() { this.refreshProductCards() this.setData({ productModalVisible: true }) }, closeProductModal() { this.setData({ 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)) || {} this.setData({ selectedProduct, 'form.productId': selectedProduct.id, 'form.manualProductTitle': '', 'form.manualProductPrice': '', 'form.durationMinutes': String(parseInt(selectedProduct.approximateDuration, 10) || this.data.form.durationMinutes || 60) }) this.closeProductModal() this.checkAvailability() }, useManualProduct() { const title = String(this.data.form.manualProductTitle || '').trim() const price = Number(this.data.form.manualProductPrice) if (!title || Number.isNaN(price) || price < 0) { wx.showToast({ title: '请填写手动预约作品名称和价格', icon: 'none' }) return } this.setData({ selectedProduct: {}, 'form.productId': '', 'form.manualProductTitle': title, 'form.manualProductPrice': String(price) }) this.closeProductModal() this.checkAvailability() }, onArtistChange(event) { const selectedArtist = this.data.artists[Number(event.detail.value)] || {} this.setData({ selectedArtist, 'form.artistId': selectedArtist.id }) 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 = Number(form.durationMinutes || 0) || 60 const startMinute = dateUtil.minutesOfDay(form.appointmentTime) 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 } } try { const calendar = await planningApi.calendar({ startDate: form.appointmentDate, endDate: form.appointmentDate, artistId: form.artistId }) const schedule = (calendar.schedules || []).find(item => isScheduleCoveringTime(item, form, startMinute, endMinute)) if (!schedule) { const tip = `${this.data.selectedArtist.name || '该美甲师'} 当前时段无可预约排班` this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } const conflicts = (calendar.appointments || []).filter(item => { if (String(item.artistId) !== String(form.artistId) || item.date !== form.appointmentDate) return false if (item.status === 3 || item.statusText === '已取消') return false const itemStart = Number(item.startMinute || dateUtil.minutesOfDay((item.startTime || '').slice(11, 16))) const itemEnd = itemStart + Number(item.durationMinutes || 60) return startMinute < itemEnd && endMinute > itemStart }) if (conflicts.length > 0) { const first = conflicts[0] const itemStart = Number(first.startMinute || dateUtil.minutesOfDay((first.startTime || '').slice(11, 16))) const itemEnd = itemStart + Number(first.durationMinutes || 60) const tip = `${this.data.selectedArtist.name || '该美甲师'} ${dateUtil.timeFromMinutes(itemStart)}-${dateUtil.timeFromMinutes(itemEnd)} 已有预约` this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } const tip = `${this.data.selectedArtist.name || '该美甲师'} ${form.appointmentTime}-${dateUtil.timeFromMinutes(endMinute)} 可预约` 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() if (!form.customerName || !form.phone || (!form.productId && !hasManualProduct) || !form.artistId) { 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, customerUserId: form.customerUserId ? String(form.customerUserId) : undefined, artistId: String(form.artistId), durationMinutes: Number(form.durationMinutes || 0) || undefined, clientRequestId: buildClientRequestId('manager-appointment') } if (form.productId) { payload.productId = String(form.productId) payload.manualProductTitle = undefined payload.manualProductPrice = undefined } else { payload.productId = undefined payload.manualProductTitle = String(form.manualProductTitle || '').trim() payload.manualProductPrice = Number(form.manualProductPrice) } const result = await planningApi.createAppointment(payload) 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 }) } }, back() { wx.navigateBack() } })