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

520 lines
15 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const planningApi = require('../../api/planning')
const { markPlanningRefresh } = require('../../utils/planning-refresh')
const { chooseImageFilePaths, uploadObjectFile, resolveUploadedImagePreviewUrl } = require('../../utils/upload')
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)
}
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)
}
return splitImageValues(value)
}
function resolveProductImageFileIds(appointment) {
if (!appointment || typeof appointment !== 'object') {
return []
}
return splitImageValues(appointment.productImageFileIds)
}
function resolveProductImageUrls(appointment) {
if (!appointment || typeof appointment !== 'object') {
return []
}
return normalizeImageUrlArray(appointment.productImageUrls)
}
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
const fileUrl = resolveUploadedImagePreviewUrl(uploadResult, filePath)
if (!fileId) {
throw new Error('预约图片上传成功但未返回文件ID')
}
fileIds.push(String(fileId))
imageUrls.push(fileUrl)
}
return { fileIds, imageUrls }
}
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 || '未知错误'}`))
}
})
})
}
Page({
data: {
id: '',
appointment: {},
avatarText: '',
timeText: '',
priceText: '未定',
detailTags: [],
productImageUrls: [],
productImageFileIds: '',
imageUploading: false,
canEditAppointment: false,
canTransferAppointment: false,
showActionRow: false,
showPendingActions: false,
showRestoreAction: false,
priceModalVisible: false,
priceSaving: false,
priceForm: {
priceText: '',
pricePending: false
},
loadError: ''
},
onLoad(options) {
this.setData({
id: options.id || '',
canTransferAppointment: canTransferAppointment()
})
this.loadDetail()
},
async loadDetail() {
try {
const appointment = await planningApi.appointment(this.data.id)
await this.applyAppointment(appointment)
} catch (error) {
this.setData({
appointment: {},
avatarText: '',
timeText: '',
priceText: '未定',
detailTags: [],
productImageUrls: [],
productImageFileIds: '',
canEditAppointment: false,
showActionRow: false,
showPendingActions: false,
showRestoreAction: false,
loadError: error.message || '预约详情加载失败'
})
}
},
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
this.setData({
appointment,
avatarText: String(appointment.customerName || '客').slice(0, 1),
timeText: `${(appointment.startTime || '').slice(0, 16)} - ${(appointment.endTime || '').slice(11, 16)}`,
priceText: formatAppointmentPrice(appointment.amount),
detailTags: buildDetailTags(appointment),
productImageUrls: imageUrls,
productImageFileIds: resolveProductImageFileIds(appointment).join(','),
canEditAppointment: Boolean(appointment.canEdit),
canTransferAppointment: canTransferAppointment(),
showActionRow: showPendingActions || showRestoreAction,
showPendingActions,
showRestoreAction,
loadError: ''
})
},
async updateStatus(status) {
try {
if (!this.data.appointment.orderId) {
throw new Error('预约订单ID为空,无法修改状态')
}
await planningApi.updateStatus(this.data.appointment.orderId, status)
markPlanningRefresh()
wx.showToast({ title: '已更新' })
await this.loadDetail()
} catch (error) {
wx.showToast({ title: error.message || '操作失败', icon: 'none' })
}
},
async complete() {
try {
const confirmed = await confirmAction('完成预约', '确认将此预约标记为已完成?', '完成', '#6f8f83')
if (confirmed) {
await this.updateStatus(STATUS_COMPLETED)
}
} catch (error) {
wx.showToast({ title: error.message || '操作失败', icon: 'none' })
}
},
async deleteAppointment() {
try {
const confirmed = await confirmAction('删除此订单', '确认删除此订单?删除后订单会进入已取消状态。', '删除', '#d98d8d')
if (confirmed) {
await this.updateStatus(STATUS_CANCELLED)
}
} catch (error) {
wx.showToast({ title: error.message || '操作失败', icon: 'none' })
}
},
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' })
}
},
goTransfer() {
if (!this.data.canTransferAppointment) {
wx.showToast({ title: '只有店长可以改派预约', icon: 'none' })
return
}
wx.navigateTo({ url: `/pages/artist-transfer/index?id=${this.data.id}` })
},
async persistAppointmentImages(fileIds, previewImageUrls) {
const imageFileIds = fileIds.join(',')
const result = await planningApi.updateAppointmentImages(this.data.id, {
imageFileIds
})
markPlanningRefresh()
if (isAppointmentResponse(result)) {
await this.applyAppointment(result)
} else {
await this.loadDetail()
}
if (Array.isArray(previewImageUrls)) {
this.setData({
productImageUrls: previewImageUrls,
productImageFileIds: imageFileIds
})
}
},
async chooseAppointmentImages() {
if (this.data.imageUploading) {
return
}
if (!this.data.canEditAppointment) {
wx.showToast({ title: '当前预约状态不可修改图片', icon: 'none' })
return
}
const currentFileIds = splitImageValues(this.data.productImageFileIds)
const remainingCount = MAX_APPOINTMENT_IMAGE_COUNT - currentFileIds.length
if (remainingCount <= 0) {
wx.showToast({ title: '最多上传 9 张作品图片', icon: 'none' })
return
}
try {
this.setData({ imageUploading: true })
const uploaded = await uploadAppointmentImageFiles(remainingCount)
if (uploaded.fileIds.length === 0) {
return
}
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
}
if (!this.data.canEditAppointment) {
wx.showToast({ title: '当前预约状态不可删除图片', icon: 'none' })
return
}
const index = Number(event.currentTarget.dataset.index)
const currentFileIds = splitImageValues(this.data.productImageFileIds)
if (currentFileIds.length === 0) {
wx.showToast({ title: '缺少图片文件ID,无法删除', icon: 'none' })
return
}
if (!Number.isInteger(index) || index < 0 || index >= currentFileIds.length) {
wx.showToast({ title: '图片序号无效,无法删除', icon: 'none' })
return
}
try {
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 })
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
})
},
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() {
},
back() {
wx.navigateBack()
}
})