Files
JayuCloud/JY-Salon-WeChat/pages/appointment-detail/index.js
T

528 lines
16 KiB
JavaScript
Raw Normal View History

2026-06-04 16:39:06 +08:00
const planningApi = require('../../api/planning')
2026-06-27 02:52:47 +08:00
const { markPlanningRefresh } = require('../../utils/planning-refresh')
2026-07-21 19:48:31 +08:00
const { chooseImageFilePaths, uploadObjectFile, resolveUploadedImagePreviewUrl } = require('../../utils/upload')
2026-07-23 01:34:35 +08:00
const MAX_APPOINTMENT_IMAGE_COUNT = 9
const SIGNED_IMAGE_EXPIRE_MINUTES = 60
const STATUS_PENDING_SERVICE = 1
const STATUS_COMPLETED = 2
const STATUS_CANCELLED = 3
function canTransferAppointment() {
const app = getApp()
const userInfo = app.globalData.userInfo || {}
return Number(userInfo.type) === 2
}
function splitImageValues(value) {
return String(value || '')
.split(',')
.map(item => item.trim())
.filter(Boolean)
}
2026-07-23 01:34:35 +08:00
function splitTagValues(value) {
return String(value || '')
.split(/[;,,、]/)
.map(item => item.trim())
.filter(Boolean)
}
function normalizeImageUrlArray(value) {
if (Array.isArray(value)) {
return value
.map(item => String(item || '').trim())
.filter(Boolean)
}
2026-07-23 01:34:35 +08:00
return splitImageValues(value)
}
function resolveProductImageFileIds(appointment) {
if (!appointment || typeof appointment !== 'object') {
return []
}
return splitImageValues(appointment.productImageFileIds || appointment.imageFileIds)
}
function resolveProductImageUrls(appointment) {
if (!appointment || typeof appointment !== 'object') {
return []
}
const productImageUrls = normalizeImageUrlArray(appointment.productImageUrls)
if (productImageUrls.length > 0) {
return productImageUrls
}
const imageUrls = normalizeImageUrlArray(appointment.imageUrls)
if (imageUrls.length > 0) {
return imageUrls
}
return normalizeImageUrlArray(appointment.productImageUrl || appointment.imageUrl)
}
async function resolveSignedImageUrls(fileIds) {
const imageUrls = []
for (let index = 0; index < fileIds.length; index += 1) {
const fileId = fileIds[index]
const signedUrl = await planningApi.signedImageUrl(fileId, SIGNED_IMAGE_EXPIRE_MINUTES)
const imageUrl = String(signedUrl || '').trim()
if (!imageUrl) {
throw new Error(`文件 ${fileId} 未返回可访问图片链接`)
}
imageUrls.push(imageUrl)
}
return imageUrls
}
async function resolveDisplayImageUrls(appointment) {
const imageUrls = resolveProductImageUrls(appointment)
if (imageUrls.length > 0) {
return imageUrls
}
const fileIds = resolveProductImageFileIds(appointment)
if (fileIds.length === 0) {
return []
}
return resolveSignedImageUrls(fileIds)
}
async function uploadAppointmentImageFiles(limit) {
const filePaths = await chooseImageFilePaths(limit)
const fileIds = []
const imageUrls = []
for (let index = 0; index < filePaths.length; index += 1) {
const filePath = filePaths[index]
const uploadResult = await uploadObjectFile(filePath)
const fileId = uploadResult.id || uploadResult.fileId
2026-07-21 19:48:31 +08:00
const fileUrl = resolveUploadedImagePreviewUrl(uploadResult, filePath)
if (!fileId) {
throw new Error('预约图片上传成功但未返回文件ID')
}
fileIds.push(String(fileId))
imageUrls.push(fileUrl)
}
return { fileIds, imageUrls }
}
2026-06-04 16:39:06 +08:00
2026-07-23 01:34:35 +08:00
function isPriceUndetermined(value) {
const amount = Number(value)
return Number.isFinite(amount) && amount === 0
}
function formatMoneyValue(value) {
const amount = Number(value)
if (!Number.isFinite(amount) || amount <= 0) {
return ''
}
return amount.toFixed(2).replace(/\.00$/, '')
}
function formatAppointmentPrice(value) {
if (value === undefined || value === null || value === '' || isPriceUndetermined(value)) {
return '未定'
}
const moneyText = formatMoneyValue(value)
return moneyText ? `¥${moneyText}` : '未定'
}
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 buildPriceForm(amount) {
const pricePending = isPriceUndetermined(amount)
return {
pricePending,
priceText: pricePending ? '' : formatMoneyValue(amount)
}
}
function buildDetailTags(appointment) {
const tags = []
const productTags = splitTagValues(appointment && appointment.productTags)
for (let index = 0; index < productTags.length; index += 1) {
tags.push({ key: `product-${index}-${productTags[index]}`, label: productTags[index], type: 'product' })
}
if (appointment && appointment.fromMeituan) {
tags.push({ key: 'source-meituan', label: '美团', type: 'source' })
}
if (appointment && appointment.needRemoval) {
tags.push({ key: 'flag-need-removal', label: '需卸甲', type: 'warning' })
}
if (appointment && appointment.depositPaid) {
tags.push({ key: 'flag-deposit-paid', label: '已交定金', type: 'paid' })
}
if (appointment && isPriceUndetermined(appointment.amount)) {
tags.push({ key: 'flag-price-pending', label: '价格未定', type: 'price' })
}
return tags
}
function isAppointmentResponse(value) {
return value && typeof value === 'object' && (value.orderItemId || value.orderId)
}
function confirmAction(title, content, confirmText, confirmColor) {
return new Promise((resolve, reject) => {
wx.showModal({
title,
content,
cancelText: '取消',
confirmText,
confirmColor,
success(result) {
resolve(Boolean(result.confirm))
},
fail(error) {
reject(new Error(`打开确认弹窗失败:${error.errMsg || '未知错误'}`))
}
})
})
}
2026-06-04 16:39:06 +08:00
Page({
data: {
id: '',
appointment: {},
avatarText: '',
2026-06-26 11:07:54 +08:00
timeText: '',
2026-07-23 01:34:35 +08:00
priceText: '未定',
detailTags: [],
productImageUrls: [],
productImageFileIds: '',
imageUploading: false,
2026-07-23 01:34:35 +08:00
canEditAppointment: false,
canTransferAppointment: false,
2026-07-23 01:34:35 +08:00
showActionRow: false,
showPendingActions: false,
showRestoreAction: false,
priceModalVisible: false,
priceSaving: false,
priceForm: {
priceText: '',
pricePending: false
},
2026-06-26 11:07:54 +08:00
loadError: ''
2026-06-04 16:39:06 +08:00
},
onLoad(options) {
this.setData({
id: options.id || '',
canTransferAppointment: canTransferAppointment()
})
2026-06-04 16:39:06 +08:00
this.loadDetail()
},
async loadDetail() {
try {
const appointment = await planningApi.appointment(this.data.id)
2026-07-23 01:34:35 +08:00
await this.applyAppointment(appointment)
2026-06-04 16:39:06 +08:00
} catch (error) {
2026-06-26 11:07:54 +08:00
this.setData({
appointment: {},
avatarText: '',
timeText: '',
2026-07-23 01:34:35 +08:00
priceText: '未定',
detailTags: [],
productImageUrls: [],
productImageFileIds: '',
2026-07-23 01:34:35 +08:00
canEditAppointment: false,
showActionRow: false,
showPendingActions: false,
showRestoreAction: false,
2026-06-26 11:07:54 +08:00
loadError: error.message || '预约详情加载失败'
})
2026-06-04 16:39:06 +08:00
}
},
2026-07-23 01:34:35 +08:00
async applyAppointment(appointment) {
if (!appointment || typeof appointment !== 'object') {
throw new Error('预约详情数据为空')
}
const imageUrls = await resolveDisplayImageUrls(appointment)
const status = Number(appointment.status)
const showPendingActions = status === STATUS_PENDING_SERVICE
const showRestoreAction = status === STATUS_COMPLETED || status === STATUS_CANCELLED
2026-06-04 16:39:06 +08:00
this.setData({
appointment,
avatarText: String(appointment.customerName || '客').slice(0, 1),
2026-06-26 11:07:54 +08:00
timeText: `${(appointment.startTime || '').slice(0, 16)} - ${(appointment.endTime || '').slice(11, 16)}`,
2026-07-23 01:34:35 +08:00
priceText: formatAppointmentPrice(appointment.amount),
detailTags: buildDetailTags(appointment),
productImageUrls: imageUrls,
2026-07-23 01:34:35 +08:00
productImageFileIds: resolveProductImageFileIds(appointment).join(','),
canEditAppointment: Boolean(appointment.canEdit),
canTransferAppointment: canTransferAppointment(),
2026-07-23 01:34:35 +08:00
showActionRow: showPendingActions || showRestoreAction,
showPendingActions,
showRestoreAction,
2026-06-26 11:07:54 +08:00
loadError: ''
2026-06-04 16:39:06 +08:00
})
},
async updateStatus(status) {
try {
2026-07-23 01:34:35 +08:00
if (!this.data.appointment.orderId) {
throw new Error('预约订单ID为空,无法修改状态')
}
2026-06-04 16:39:06 +08:00
await planningApi.updateStatus(this.data.appointment.orderId, status)
2026-06-27 02:52:47 +08:00
markPlanningRefresh()
2026-06-04 16:39:06 +08:00
wx.showToast({ title: '已更新' })
2026-07-23 01:34:35 +08:00
await this.loadDetail()
2026-06-04 16:39:06 +08:00
} catch (error) {
wx.showToast({ title: error.message || '操作失败', icon: 'none' })
}
},
2026-07-23 01:34:35 +08:00
async complete() {
try {
const confirmed = await confirmAction('完成预约', '确认将此预约标记为已完成?', '完成', '#6f8f83')
if (confirmed) {
await this.updateStatus(STATUS_COMPLETED)
}
} catch (error) {
wx.showToast({ title: error.message || '操作失败', icon: 'none' })
}
2026-06-04 16:39:06 +08:00
},
2026-07-23 01:34:35 +08:00
async deleteAppointment() {
try {
const confirmed = await confirmAction('删除此订单', '确认删除此订单?删除后订单会进入已取消状态。', '删除', '#d98d8d')
if (confirmed) {
await this.updateStatus(STATUS_CANCELLED)
}
} catch (error) {
wx.showToast({ title: error.message || '操作失败', icon: 'none' })
}
2026-06-04 16:39:06 +08:00
},
2026-07-23 01:34:35 +08:00
async restorePending() {
try {
const confirmed = await confirmAction('修改状态', '确认将此预约改回待完成?', '修改', '#6f8f83')
if (confirmed) {
await this.updateStatus(STATUS_PENDING_SERVICE)
}
} catch (error) {
wx.showToast({ title: error.message || '操作失败', icon: 'none' })
}
2026-06-04 16:39:06 +08:00
},
goTransfer() {
if (!this.data.canTransferAppointment) {
wx.showToast({ title: '只有店长可以改派预约', icon: 'none' })
return
}
2026-06-04 16:39:06 +08:00
wx.navigateTo({ url: `/pages/artist-transfer/index?id=${this.data.id}` })
},
2026-07-21 19:48:31 +08:00
async persistAppointmentImages(fileIds, previewImageUrls) {
2026-07-23 01:34:35 +08:00
const result = await planningApi.updateAppointmentImages(this.data.id, {
imageFileIds: fileIds.join(',')
})
markPlanningRefresh()
2026-07-23 01:34:35 +08:00
if (isAppointmentResponse(result)) {
await this.applyAppointment(result)
} else {
await this.loadDetail()
}
2026-07-21 19:48:31 +08:00
if (Array.isArray(previewImageUrls) && previewImageUrls.length > 0) {
this.setData({ productImageUrls: previewImageUrls })
}
},
async chooseAppointmentImages() {
if (this.data.imageUploading) {
return
}
2026-07-23 01:34:35 +08:00
if (!this.data.canEditAppointment) {
wx.showToast({ title: '当前预约状态不可修改图片', icon: 'none' })
return
}
const currentFileIds = splitImageValues(this.data.productImageFileIds)
2026-07-23 01:34:35 +08:00
const remainingCount = MAX_APPOINTMENT_IMAGE_COUNT - currentFileIds.length
if (remainingCount <= 0) {
wx.showToast({ title: '最多上传 9 张作品图片', icon: 'none' })
return
}
try {
2026-07-23 01:34:35 +08:00
const confirmed = await confirmAction('上传图片', '确认添加作品图片到此预约?', '上传', '#6f8f83')
if (!confirmed) {
return
}
this.setData({ imageUploading: true })
const uploaded = await uploadAppointmentImageFiles(remainingCount)
if (uploaded.fileIds.length === 0) {
return
}
2026-07-21 19:48:31 +08:00
await this.persistAppointmentImages(
currentFileIds.concat(uploaded.fileIds),
this.data.productImageUrls.concat(uploaded.imageUrls)
)
wx.showToast({ title: '图片已保存' })
} catch (error) {
wx.showToast({ title: error.message || '图片上传失败', icon: 'none' })
} finally {
this.setData({ imageUploading: false })
}
},
async removeAppointmentImage(event) {
if (this.data.imageUploading) {
return
}
2026-07-23 01:34:35 +08:00
if (!this.data.canEditAppointment) {
wx.showToast({ title: '当前预约状态不可删除图片', icon: 'none' })
return
}
const index = Number(event.currentTarget.dataset.index)
const currentFileIds = splitImageValues(this.data.productImageFileIds)
2026-07-23 01:34:35 +08:00
if (currentFileIds.length === 0) {
wx.showToast({ title: '缺少图片文件ID,无法删除', icon: 'none' })
return
}
if (!Number.isInteger(index) || index < 0 || index >= currentFileIds.length) {
2026-07-23 01:34:35 +08:00
wx.showToast({ title: '图片序号无效,无法删除', icon: 'none' })
return
}
try {
2026-07-23 01:34:35 +08:00
const confirmed = await confirmAction('删除图片', '确认删除这张作品图片?', '删除', '#d98d8d')
if (!confirmed) {
return
}
const currentImageUrls = Array.isArray(this.data.productImageUrls) ? this.data.productImageUrls : []
const nextFileIds = currentFileIds.filter((item, itemIndex) => itemIndex !== index)
const nextImageUrls = currentImageUrls.filter((item, itemIndex) => itemIndex !== index)
this.setData({ imageUploading: true })
2026-07-21 19:48:31 +08:00
await this.persistAppointmentImages(nextFileIds, nextImageUrls)
wx.showToast({ title: '图片已保存' })
} catch (error) {
wx.showToast({ title: error.message || '图片保存失败', icon: 'none' })
} finally {
this.setData({ imageUploading: false })
}
},
previewProductImage(event) {
const current = this.data.productImageUrls[Number(event.currentTarget.dataset.index)]
if (!current) {
return
}
wx.previewImage({
current,
urls: this.data.productImageUrls
})
},
2026-07-23 01:34:35 +08:00
openPriceEditor() {
if (this.data.priceSaving) {
return
}
if (!this.data.canEditAppointment) {
wx.showToast({ title: '当前预约状态不可修改价格', icon: 'none' })
return
}
this.setData({
priceModalVisible: true,
priceForm: buildPriceForm(this.data.appointment.amount)
})
},
closePriceEditor() {
if (this.data.priceSaving) {
return
}
this.setData({ priceModalVisible: false })
},
onPriceInput(event) {
const value = sanitizePriceInput(event.detail.value)
this.setData({ 'priceForm.priceText': value })
return value
},
togglePricePending() {
if (this.data.priceSaving) {
return
}
const pricePending = !this.data.priceForm.pricePending
const patch = {
'priceForm.pricePending': pricePending
}
if (pricePending) {
patch['priceForm.priceText'] = ''
}
this.setData(patch)
},
async savePrice() {
if (this.data.priceSaving) {
return
}
const form = this.data.priceForm
const priceText = form.pricePending ? '0' : normalizeConfirmedPrice(form.priceText)
if (!priceText) {
wx.showToast({ title: '请填写正确的价格', icon: 'none' })
return
}
const price = Number(priceText)
const priceLabel = price === 0 ? '未定' : `¥${formatMoneyValue(price)}`
try {
const confirmed = await confirmAction('保存价格', `确认将本次价格保存为${priceLabel}?`, '保存', '#6f8f83')
if (!confirmed) {
return
}
this.setData({ priceSaving: true })
const result = await planningApi.updateAppointmentPrice(this.data.id, {
price
})
markPlanningRefresh()
if (isAppointmentResponse(result)) {
await this.applyAppointment(result)
} else {
await this.loadDetail()
}
this.setData({ priceModalVisible: false })
wx.showToast({ title: '价格已保存' })
} catch (error) {
wx.showToast({ title: error.message || '价格保存失败', icon: 'none' })
} finally {
this.setData({ priceSaving: false })
}
},
stopTap() {
},
2026-06-04 16:39:06 +08:00
back() {
wx.navigateBack()
}
})