const planningApi = require('../../api/planning') const employeesApi = require('../../api/employees') const productsApi = require('../../api/products') const customersApi = require('../../api/customers') const dateUtil = require('../../utils/date') const { uploadObjectFile } = require('../../utils/upload') function normalizeProduct(product, artists) { const artistIds = String(product.bookableArtists || '').split(',').map(id => id.trim()).filter(Boolean) const artistNames = artistIds.map(id => artists.find(artist => String(artist.id) === id)).filter(Boolean).map(artist => artist.name) const imageUrls = Array.isArray(product.imageUrls) ? product.imageUrls : [] const tags = Array.isArray(product.tagList) ? product.tagList : String(product.tags || '').split(/[;,,、]/).map(tag => tag.trim()).filter(Boolean) return { ...product, title: product.title || '未命名款式', coverImage: imageUrls[0] || '', priceText: product.price == null ? '价格待定' : `¥${product.price}`, durationText: product.approximateDuration || (product.serviceDurationMinutes ? `${product.serviceDurationMinutes}分钟` : '时长待定'), artistText: artistIds.length ? artistNames.join('、') || `${artistIds.length}位美甲师可做` : '全部美甲师', tagList: tags.slice(0, 3) } } function normalizeCustomer(customer) { const name = customer.nickname || customer.name || customer.account || '' const phone = customer.contactPhone || customer.phone || '' return { ...customer, id: customer.id, name, phone, title: name || phone || '客户', subtitle: phone || '未填写手机号' } } function imagePatch(images) { const normalized = (images || []).slice(0, 9) return { 'form.manualProductImages': normalized, 'form.manualProductImageFileIds': normalized.map(image => image.fileId).filter(Boolean).join(','), 'form.manualProductImageUrl': normalized[0] ? normalized[0].previewUrl || normalized[0].fileUrl || '' : '' } } function chooseImages(count) { return new Promise((resolve, reject) => wx.chooseMedia({ count: Math.min(9, Math.max(1, count)), mediaType: ['image'], sourceType: ['album', 'camera'], sizeType: ['compressed'], success: result => resolve((result.tempFiles || []).map(file => file.tempFilePath).filter(Boolean)), fail: error => String(error && error.errMsg || '').includes('cancel') ? resolve([]) : reject(new Error(`选择图片失败:${error && error.errMsg || '未知错误'}`)) })) } Page({ data: { form: { serviceDate: dateUtil.formatDate(new Date()), serviceTime: '', artistId: '', productId: '', manualProductTitle: '', manualProductDescription: '', manualProductTags: '', manualProductTargetAudience: '', manualProductPrecautions: '', manualProductImageFileIds: '', manualProductImageUrl: '', manualProductImages: [], customerUserId: '', customerName: '', wechatId: '', phone: '', amount: '', durationMinutes: '60', status: 4, remark: '' }, manualProductDraft: { title: '', price: '', durationMinutes: '60', description: '' }, artists: [], artistOptions: [], products: [], productOptions: [], allCustomerOptions: [], customerOptions: [], productSelectorVisible: false, manualProductSheetVisible: false, artistSelectorVisible: false, customerSelectorVisible: false, loadingProducts: false, loadingArtists: false, loadingCustomers: false, manualImageUploading: false, submitting: false, productKeyword: '', artistKeyword: '', customerKeyword: '', productError: '', artistError: '', customerError: '', selectedArtistName: '', selectedProduct: {}, selectedProductTitle: '', selectedProductPriceText: '', manualProductTitleLength: 0, manualProductMoreVisible: false }, onLoad(options = {}) { const serviceDate = options.serviceDate || this.data.form.serviceDate; const artistId = options.artistId || ''; this._entryDefaults = { serviceDate, artistId }; this.setData({ 'form.serviceDate': serviceDate, 'form.artistId': artistId }); this.loadArtists(options.artistId); this.loadProducts(); this.loadCustomers() }, async resetForm() { if (this.data.submitting) return if (this.data.manualImageUploading) { wx.showToast({ title: '图片上传中,请稍后再恢复默认值', icon: 'none' }) return } const result = await new Promise(resolve => wx.showModal({ title: '恢复默认值', content: '将清除本次补录内容,但不会删除已上传图片文件。保留入口带入的日期和美甲师,确定继续吗?', cancelText: '继续填写', confirmText: '恢复默认', success: resolve, fail: () => resolve({ confirm: false }) })) if (!result.confirm) return const defaults = this._entryDefaults || {} const artistId = defaults.artistId || '' const artist = this.data.artists.find(item => String(item.id) === String(artistId)) this.setData({ form: { serviceDate: defaults.serviceDate || dateUtil.formatDate(new Date()), serviceTime: '', artistId, productId: '', manualProductTitle: '', manualProductDescription: '', manualProductTags: '', manualProductTargetAudience: '', manualProductPrecautions: '', manualProductImageFileIds: '', manualProductImageUrl: '', manualProductImages: [], customerUserId: '', customerName: '', wechatId: '', phone: '', amount: '', durationMinutes: '60', status: 4, remark: '' }, manualProductDraft: { title: '', price: '', durationMinutes: '60', description: '' }, selectedArtistName: artist ? artist.name : '', selectedProduct: {}, selectedProductTitle: '', selectedProductPriceText: '', manualProductTitleLength: 0, manualProductMoreVisible: false, productKeyword: '', artistKeyword: '', customerKeyword: '', customerSelectorVisible: false, artistSelectorVisible: false, productSelectorVisible: false, manualProductSheetVisible: false }) }, async loadArtists(preferredArtistId) { this.setData({ loadingArtists: true }); try { const result = await employeesApi.list({ page: 1, size: 100 }); const list = result.list || result || []; const artists = list.map(item => ({ ...item, name: item.name || item.nickname || item.account || `美甲师${item.id}` })); const selected = artists.find(item => String(item.id) === String(preferredArtistId || this.data.form.artistId)); this.setData({ artists, artistOptions: artists.map(item => ({ id: item.id, title: item.name, subtitle: item.phone || '' })), selectedArtistName: selected ? selected.name : '', 'form.artistId': selected ? selected.id : '', artistError: '' }); this.refreshProductOptions() } catch (error) { this.setData({ artists: [], artistOptions: [], artistError: error.message || '美甲师加载失败' }) } finally { this.setData({ loadingArtists: false }) } }, async loadProducts() { this.setData({ loadingProducts: true }); try { const result = await productsApi.list({ page: 1, size: 100 }); this.setData({ products: result.list || result || [], productError: '' }); this.refreshProductOptions() } catch (error) { this.setData({ products: [], productOptions: [], productError: error.message || '款式加载失败' }) } finally { this.setData({ loadingProducts: false }) } }, refreshProductOptions() { const keyword = String(this.data.productKeyword || '').trim().toLowerCase(); const all = (this.data.products || []).map(product => normalizeProduct(product, this.data.artists)); this.setData({ productOptions: all.filter(item => !keyword || `${item.title} ${item.artistText} ${item.durationText} ${item.tagList.join(' ')}`.toLowerCase().includes(keyword)) }) }, async loadCustomers() { this.setData({ loadingCustomers: true }); try { const result = customersApi.listForAppointment ? await customersApi.listForAppointment({ page: 1, size: 100 }) : await customersApi.list({ page: 1, size: 100 }); const options = (result.list || result || []).map(normalizeCustomer); this.setData({ allCustomerOptions: options, customerOptions: options, customerError: '' }) } catch (error) { this.setData({ customerError: error.message || '客户加载失败' }) } finally { this.setData({ loadingCustomers: false }) } }, openProductSelector() { this.setData({ manualProductSheetVisible: true, manualProductTitleLength: String(this.data.manualProductDraft.title || '').length }) }, openProductLibrary() { this.setData({ manualProductSheetVisible: false, productSelectorVisible: true }) }, closeProductSelector() { this.setData({ productSelectorVisible: false }) }, closeManualProduct() { this.setData({ manualProductSheetVisible: false }) }, openManualProduct() { this.setData({ productSelectorVisible: false, manualProductSheetVisible: true, manualProductMoreVisible: false }) }, toggleManualProductMore() { this.setData({ manualProductMoreVisible: !this.data.manualProductMoreVisible }) }, onManualProductInput(event) { const field = event.currentTarget.dataset.field; const patch = { [`manualProductDraft.${field}`]: event.detail.value }; if (field === 'title') { patch.manualProductTitleLength = String(event.detail.value || '').length; if (this.data.form.productId) { patch['form.productId'] = ''; patch.selectedProduct = {}; patch.selectedProductTitle = ''; patch.selectedProductPriceText = '' } } this.setData(patch) }, stopTap() {}, stopTouchMove() {}, openArtistSelector() { this.setData({ artistSelectorVisible: true }) }, closeArtistSelector() { this.setData({ artistSelectorVisible: false }) }, openCustomerSelector() { this.setData({ customerSelectorVisible: true }) }, closeCustomerSelector() { this.setData({ customerSelectorVisible: false }) }, searchProducts(event) { const keyword = String(event.detail.value || '').trim().toLowerCase(); this.setData({ productKeyword: keyword }); this.refreshProductOptions() }, searchArtists(event) { const keyword = String(event.detail.value || '').toLowerCase(); this.setData({ artistKeyword: keyword, artistOptions: this.data.artists.map(item => ({ id: item.id, title: item.name, subtitle: item.phone || '' })).filter(item => !keyword || item.title.toLowerCase().includes(keyword)) }) }, searchCustomers(event) { const keyword = String(event.detail.value || '').toLowerCase(); this.setData({ customerKeyword: keyword, customerOptions: this.data.allCustomerOptions.filter(item => !keyword || `${item.name} ${item.phone}`.toLowerCase().includes(keyword)) }) }, selectProduct(event) { const item = event.detail.item || {}; const duration = String(item.serviceDurationMinutes || String(item.approximateDuration || '').replace(/[^0-9]/g, '') || '60'); this.setData({ 'form.productId': item.id, 'form.manualProductTitle': '', 'form.amount': item.price == null ? this.data.form.amount : String(item.price), 'form.durationMinutes': duration, selectedProduct: item, selectedProductTitle: item.title, selectedProductPriceText: item.priceText || '价格待定', manualProductDraft: { title: '', price: '', durationMinutes: duration, description: '' }, productSelectorVisible: false, manualProductSheetVisible: false }) }, selectArtist(event) { const item = event.detail.item; this.setData({ 'form.artistId': item.id, selectedArtistName: item.title, artistSelectorVisible: false }) }, selectCustomer(event) { const item = event.detail.item || {}; this.setData({ 'form.customerUserId': item.id, 'form.customerName': item.name || item.title, 'form.phone': item.phone || '', customerSelectorVisible: false }) }, useWalkIn() { this.setData({ 'form.customerUserId': '', 'form.customerName': '', 'form.wechatId': '', 'form.phone': '', customerSelectorVisible: false }) }, onCustomerInput(event) { this.setData({ [`form.${event.currentTarget.dataset.field}`]: event.detail.value, 'form.customerUserId': '' }) }, useManualProduct() { const title = String(this.data.manualProductDraft.title || '').trim(); const priceText = String(this.data.manualProductDraft.price || this.data.form.amount || '').trim(); const price = Number(priceText); const images = this.data.form.manualProductImages || []; if (this.data.form.productId) { if (!priceText || !Number.isFinite(price) || price < 0) { wx.showToast({ title: '请输入正确的款式价格', icon: 'none' }); return } this.setData({ 'form.amount': priceText, 'form.durationMinutes': String(this.data.manualProductDraft.durationMinutes || '60'), manualProductSheetVisible: false }); return } if (!title && !images.length) { wx.showToast({ title: '请填写款式名称或添加图片', icon: 'none' }); return } if (!priceText || !Number.isFinite(price) || price < 0) { wx.showToast({ title: '请输入正确的款式价格', icon: 'none' }); return } const duration = String(this.data.manualProductDraft.durationMinutes || '60'); this.setData({ 'form.productId': '', 'form.manualProductTitle': title, 'form.manualProductDescription': this.data.manualProductDraft.description || '', 'form.manualProductPrice': priceText, 'form.amount': priceText, 'form.durationMinutes': duration, 'manualProductDraft.price': priceText, selectedProduct: {}, selectedProductTitle: title, selectedProductPriceText: `¥${price}`, productSelectorVisible: false, manualProductSheetVisible: false }) }, async chooseManualProductImage() { if (this.data.manualImageUploading) return; const remaining = 9 - (this.data.form.manualProductImages || []).length; if (remaining <= 0) { wx.showToast({ title: '最多添加9张图片', icon: 'none' }); return } try { this.setData({ manualImageUploading: true }); const paths = await chooseImages(remaining); for (const filePath of paths) { const result = await uploadObjectFile(filePath); const fileId = result.id || result.fileId; if (!fileId) throw new Error('图片上传成功但未返回文件ID'); this.setData(imagePatch((this.data.form.manualProductImages || []).concat({ fileId: String(fileId), fileUrl: result.fileUrl || result.primaryUrl || '', previewUrl: filePath }))) } } catch (error) { wx.showToast({ title: error.message || '图片上传失败', icon: 'none' }) } finally { this.setData({ manualImageUploading: false }) } }, removeManualProductImage(event) { const index = Number(event.currentTarget.dataset.index); this.setData(imagePatch((this.data.form.manualProductImages || []).filter((item, itemIndex) => itemIndex !== index))) }, onManualProductImageError(event) { const index = Number(event.currentTarget.dataset.index); const images = this.data.form.manualProductImages || []; if (!images[index] || !images[index].fileUrl) return; const fallback = images.slice(); fallback[index] = { ...fallback[index], previewUrl: fallback[index].fileUrl }; this.setData(imagePatch(fallback)) }, onSelectedProductImageError() { this.setData({ 'selectedProduct.coverImage': '' }) }, onInput(event) { const field = event.currentTarget.dataset.field; const value = event.detail.value; this.setData({ [`form.${field}`]: value, ...(field === 'amount' ? { 'manualProductDraft.price': value } : {}) }) }, onDateChange(event) { this.setData({ 'form.serviceDate': event.detail.value }) }, onTimeChange(event) { this.setData({ 'form.serviceTime': event.detail.value }) }, selectStatus(event) { this.setData({ 'form.status': Number(event.currentTarget.dataset.status) }) }, async submit() { const form = this.data.form; if (!form.serviceDate || (!form.productId && !String(form.manualProductTitle || '').trim() && !(form.manualProductImages || []).length) || !String(form.amount || '').trim() || !form.artistId) { wx.showToast({ title: '请补全款式、金额、日期和美甲师', icon: 'none' }); return } if (form.phone && !/^1[3-9]\d{9}$/.test(String(form.phone).trim())) { wx.showToast({ title: '请输入正确手机号', icon: 'none' }); return } this.setData({ submitting: true }); try { const payload = { ...form, amount: Number(form.amount), manualProductPrice: Number(form.manualProductPrice || form.amount), durationMinutes: Number(form.durationMinutes) || 60, manualProductImageFileIds: String(form.manualProductImageFileIds || '').trim() || undefined, customerName: String(form.customerName || '').trim() || undefined, wechatId: String(form.wechatId || '').trim() || undefined, phone: String(form.phone || '').trim() || undefined, serviceTime: String(form.serviceTime || '').trim() || undefined }; if (!payload.manualProductTitle && payload.manualProductImageFileIds) payload.manualProductTitle = String(form.customerName || '').trim() || '散客款式'; await planningApi.createBackfillOrder(payload); wx.showToast({ title: '历史补单已保存', icon: 'success' }); const app = getApp(); app.globalData.planningNeedRefresh = true; setTimeout(() => wx.navigateBack(), 500) } catch (error) { wx.showToast({ title: error.message || '保存失败', icon: 'none' }) } finally { this.setData({ submitting: false }) } } })