Files
JayuCloud/JY-Salon-WeChat/pages/shop-settings/index.js
T

669 lines
22 KiB
JavaScript

const shopApi = require('../../api/shop')
const tagsApi = require('../../api/tags')
const dateUtil = require('../../utils/date')
const { BRAND_CONFIG } = require('../../utils/config')
const { markPlanningRefresh } = require('../../utils/planning-refresh')
const { chooseImageFilePaths, chooseImageFilePath, uploadObjectFile, resolveUploadedImagePreviewUrl } = require('../../utils/upload')
const PRESETS = [
{ value: 'EVERYDAY', label: '全周营业', workDays: [1, 2, 3, 4, 5, 6, 7], startTime: '10:00', endTime: '22:00' },
{ value: 'DOUBLE_REST', label: '双休', workDays: [1, 2, 3, 4, 5], startTime: '09:00', endTime: '18:00' },
{ value: 'SINGLE_REST', label: '单休', workDays: [1, 2, 3, 4, 5, 6], startTime: '10:00', endTime: '22:00' },
{ value: 'CUSTOM', label: '自定义', workDays: [1, 2, 3, 4, 5], startTime: '10:00', endTime: '22:00' }
]
const WEEKDAYS = [
{ value: 1, label: '周一' },
{ value: 2, label: '周二' },
{ value: 3, label: '周三' },
{ value: 4, label: '周四' },
{ value: 5, label: '周五' },
{ value: 6, label: '周六' },
{ value: 7, label: '周日' }
]
const EXCEPTION_TYPES = [
{ value: 'REST', label: '休息' },
{ value: 'EXTRA_WORK', label: '临时营业' },
{ value: 'CHANGE_SHIFT', label: '临时改班' }
]
const DEFAULT_SHOP_INTRO = '专注法式、晕染与手绘设计,适合想要温柔质感的客人。'
function copyWorkDays(days) {
if (Array.isArray(days)) {
return days.map(day => Number(day)).filter(day => day >= 1 && day <= 7).sort()
}
return String(days || '')
.split(',')
.map(day => Number(String(day).trim()))
.filter(day => day >= 1 && day <= 7)
.sort()
}
function encodeWorkDays(days) {
return Array.from(new Set(copyWorkDays(days))).join(',')
}
function buildPreset(value) {
return PRESETS.find(item => item.value === value) || PRESETS[0]
}
function buildPresetOptions(presetType) {
return PRESETS.map(item => ({ ...item, active: item.value === presetType }))
}
function buildWeekdayOptions(workDays) {
const selected = copyWorkDays(workDays)
return WEEKDAYS.map(item => ({ ...item, active: selected.includes(item.value) }))
}
function exceptionTypeLabel(value) {
const option = EXCEPTION_TYPES.find(item => item.value === value)
return option ? option.label : '特殊日期'
}
function buildExceptionSummary(item) {
if (item.exceptionType === 'REST') {
return `${item.workDate} 店铺休息`
}
return `${item.workDate} ${exceptionTypeLabel(item.exceptionType)} ${String(item.startTime || '').slice(0, 5)}-${String(item.endTime || '').slice(0, 5)}`
}
function resolveFirstImageUrl(urls) {
return Array.isArray(urls) ? String(urls[0] || '').trim() : ''
}
function normalizeImageUrls(urls) {
return Array.isArray(urls) ? urls.map(url => String(url || '').trim()).filter(Boolean) : []
}
function introLength(value) {
return String(value || '').length
}
function parseFileIds(value) {
return String(value || '')
.split(',')
.map(item => String(item || '').trim())
.filter(Boolean)
}
function joinFileIds(fileIds) {
return (Array.isArray(fileIds) ? fileIds : []).map(item => String(item || '').trim()).filter(Boolean).join(',')
}
function normalizeGalleryItems(fileIds, urls) {
const normalizedFileIds = parseFileIds(fileIds)
const normalizedUrls = normalizeImageUrls(urls)
return normalizedFileIds.map((fileId, index) => ({
fileId,
url: normalizedUrls[index] || ''
}))
}
function normalizeTagOption(tag) {
const name = String((tag && (tag.displayName || tag.tagName || tag.name)) || '').trim()
if (!name) {
return null
}
return {
id: (tag && tag.id) || name,
name,
tagName: (tag && tag.tagName) || name,
displayName: (tag && tag.displayName) || name,
textColor: (tag && tag.textColor) || '#333333',
bgColor: (tag && tag.bgColor) || '#FFFFFF',
borderColor: (tag && tag.borderColor) || '#E5E5E5'
}
}
function normalizeTagOptions(tags) {
const names = new Set()
return (Array.isArray(tags) ? tags : [])
.map(normalizeTagOption)
.filter(Boolean)
.filter(item => {
if (names.has(item.name)) {
return false
}
names.add(item.name)
return true
})
}
function buildWorkDaysText(days) {
const selected = copyWorkDays(days)
if (selected.length === 7) {
return '周一至周日'
}
return selected.map(day => WEEKDAYS.find(item => item.value === day)).filter(Boolean).map(item => item.label).join('、') || '未设置营业日'
}
function resolveBusinessStatus(settings) {
if (Number(settings.status) === 0) {
return {
text: '已停用',
className: 'closed'
}
}
if (settings.authorizationExpired) {
return {
text: '授权到期',
className: 'warning'
}
}
return {
text: '营业中',
className: 'open'
}
}
function buildShopPayload(settings, form) {
const workDays = copyWorkDays(form.scheduleWorkDays)
return {
shopName: settings.shopName || settings.name || '',
description: settings.description || '',
address: settings.address || '',
mapProvider: settings.mapProvider || '',
longitude: settings.longitude,
latitude: settings.latitude,
businessHours: `${form.startTime}-${form.endTime}`,
schedulePresetType: form.schedulePresetType,
scheduleWorkDays: encodeWorkDays(workDays),
scheduleRemark: String(form.scheduleRemark || '').trim(),
coverImageFileId: String(settings.coverImageFileId || '').trim(),
imageFileIds: String(settings.imageFileIds || '').trim(),
themePrimaryColor: settings.themePrimaryColor || '',
themeSecondaryColor: settings.themeSecondaryColor || '',
themeAccentColor: settings.themeAccentColor || '',
themePageBgColor: settings.themePageBgColor || '',
themeCardBgColor: settings.themeCardBgColor || '',
themeBackgroundImageFileId: settings.themeBackgroundImageFileId || '',
status: settings.status,
authorizationStartDate: settings.authorizationStartDate,
authorizationDays: settings.authorizationDays,
authorizationExpireTime: settings.authorizationExpireTime
}
}
function buildProfilePayload(settings, profileForm) {
return {
shopName: String(profileForm.shopName || '').trim(),
description: String(profileForm.rule || '').trim(),
address: String(profileForm.address || '').trim(),
mapProvider: settings.mapProvider || '',
longitude: settings.longitude,
latitude: settings.latitude,
businessHours: settings.businessHours || '',
schedulePresetType: settings.schedulePresetType || '',
scheduleWorkDays: settings.scheduleWorkDays || '',
scheduleRemark: settings.scheduleRemark || '',
coverImageFileId: String(profileForm.coverImageFileId || '').trim(),
imageFileIds: joinFileIds(profileForm.galleryFileIds),
themePrimaryColor: settings.themePrimaryColor || '',
themeSecondaryColor: settings.themeSecondaryColor || '',
themeAccentColor: settings.themeAccentColor || '',
themePageBgColor: settings.themePageBgColor || '',
themeCardBgColor: settings.themeCardBgColor || '',
themeBackgroundImageFileId: settings.themeBackgroundImageFileId || '',
status: settings.status,
authorizationStartDate: settings.authorizationStartDate,
authorizationDays: settings.authorizationDays,
authorizationExpireTime: settings.authorizationExpireTime
}
}
function resolveForm(settings) {
const hours = String(settings.businessHours || '').split('-')
const preset = buildPreset(settings.schedulePresetType || 'EVERYDAY')
return {
startTime: String(settings.startTime || hours[0] || preset.startTime).slice(0, 5),
endTime: String(settings.endTime || hours[1] || preset.endTime).slice(0, 5),
schedulePresetType: settings.schedulePresetType || preset.value,
scheduleWorkDays: copyWorkDays(settings.scheduleWorkDays || preset.workDays),
scheduleRemark: settings.scheduleRemark || ''
}
}
Page({
data: {
loading: false,
loaded: false,
saving: false,
coverUploading: false,
galleryUploading: false,
profileSheetVisible: false,
activeProfileField: 'shopName',
profileSheetTitle: '修改店铺名称',
profileSheetSaveText: '保存名称',
scheduleSheetVisible: false,
activeScheduleTab: 'RULE',
shopName: BRAND_CONFIG.defaultShopName,
shopDescription: DEFAULT_SHOP_INTRO,
shopAddress: '暂未填写地址',
businessStatusText: '营业中',
businessStatusClass: 'open',
coverImagePreviewUrl: '',
imageCountText: '暂无图片',
galleryItems: [],
introLength: introLength(DEFAULT_SHOP_INTRO),
tagList: [],
tagCountText: '暂无标签',
scheduleSummary: '营业时间未设置',
scheduleRemarkText: '点击设置营业日和营业时间',
exceptionCountText: '特殊日期 · 0 条',
exceptionSummary: '暂无特殊日期',
exceptions: [],
settingsSnapshot: {},
presetOptions: buildPresetOptions('EVERYDAY'),
weekdayOptions: buildWeekdayOptions([1, 2, 3, 4, 5, 6, 7]),
exceptionTypes: EXCEPTION_TYPES,
exceptionTypeIndex: 0,
exceptionTypeLabel: '休息',
form: {
startTime: '10:00',
endTime: '22:00',
schedulePresetType: 'EVERYDAY',
scheduleWorkDays: [1, 2, 3, 4, 5, 6, 7],
scheduleRemark: ''
},
profileForm: {
shopName: BRAND_CONFIG.defaultShopName,
rule: DEFAULT_SHOP_INTRO,
address: '',
galleryFileIds: [],
coverImageFileId: ''
},
exceptionForm: {
workDate: dateUtil.formatDate(new Date()),
exceptionType: 'REST',
startTime: '10:00',
endTime: '18:00',
remark: ''
}
},
onLoad() {
this.loadSettings()
},
onShow() {
if (this.data.loaded) {
this.loadSettings()
}
},
async loadSettings() {
this.setData({ loading: true })
try {
const [settings, exceptions, tagsData] = await Promise.all([
shopApi.settings(),
shopApi.scheduleExceptions(),
tagsApi.listAll()
])
const form = resolveForm(settings || {})
const status = resolveBusinessStatus(settings || {})
const imageUrls = normalizeImageUrls(settings.imageUrls)
const galleryItems = normalizeGalleryItems(settings.imageFileIds, settings.imageUrls)
const profileForm = {
shopName: settings.shopName || settings.name || this.data.profileForm.shopName,
rule: settings.description || DEFAULT_SHOP_INTRO,
address: settings.address || '',
galleryFileIds: galleryItems.map(item => item.fileId),
coverImageFileId: settings.coverImageFileId || ''
}
const exceptionList = (exceptions || []).map(item => ({
...item,
startTime: item.startTime ? String(item.startTime).slice(0, 5) : '',
endTime: item.endTime ? String(item.endTime).slice(0, 5) : '',
summary: buildExceptionSummary(item)
}))
const tagList = normalizeTagOptions(tagsData.list || tagsData || [])
this.setData({
loaded: true,
settingsSnapshot: settings || {},
shopName: settings.shopName || settings.name || this.data.shopName,
shopDescription: settings.description || DEFAULT_SHOP_INTRO,
shopAddress: settings.address || '暂未填写地址',
businessStatusText: status.text,
businessStatusClass: status.className,
coverImagePreviewUrl: resolveFirstImageUrl(settings.coverImageUrls),
imageCountText: imageUrls.length ? `已上传 ${imageUrls.length} 张图片` : '暂无图片',
galleryItems,
profileForm,
introLength: introLength(profileForm.rule),
tagList,
tagCountText: tagList.length ? `${tagList.length} 个标签` : '暂无标签',
scheduleSummary: `${buildWorkDaysText(form.scheduleWorkDays)} · ${form.startTime} - ${form.endTime}`,
scheduleRemarkText: form.scheduleRemark || '全周营业规则',
exceptionCountText: `特殊日期 · ${exceptionList.length} 条`,
exceptionSummary: exceptionList[0] ? exceptionList[0].summary : '暂无特殊日期',
exceptions: exceptionList,
form,
presetOptions: buildPresetOptions(form.schedulePresetType),
weekdayOptions: buildWeekdayOptions(form.scheduleWorkDays)
})
} catch (error) {
wx.showToast({ title: error.message || '店铺设置加载失败', icon: 'none' })
} finally {
this.setData({ loading: false })
}
},
openProfileSheet(event) {
this.openProfileSheetByField(event.currentTarget.dataset.field || 'shopName')
},
openProfileSheetByField(field) {
const titleMap = {
shopName: '修改店铺名称',
rule: '修改店铺简介',
address: '修改店铺地址',
cover: '修改店铺主图',
gallery: '修改环境照片'
}
const saveTextMap = {
shopName: '保存名称',
rule: '保存简介',
address: '保存地址',
cover: '保存主图',
gallery: '保存照片'
}
this.setData({
profileSheetVisible: true,
activeProfileField: titleMap[field] ? field : 'shopName',
profileSheetTitle: titleMap[field] || titleMap.shopName,
profileSheetSaveText: saveTextMap[field] || saveTextMap.shopName
})
},
closeProfileSheet() {
if (this.data.saving || this.data.coverUploading || this.data.galleryUploading) {
return
}
this.setData({ profileSheetVisible: false })
},
onProfileInput(event) {
const field = event.currentTarget.dataset.field
const value = event.detail.value
const nextData = { [`profileForm.${field}`]: value }
if (field === 'rule') {
nextData.introLength = introLength(value)
}
this.setData(nextData)
},
async chooseCoverImage() {
if (this.data.coverUploading || this.data.galleryUploading || this.data.saving) {
return
}
try {
const filePath = await chooseImageFilePath()
if (!filePath) {
return
}
this.setData({ coverUploading: true })
const uploadResult = await uploadObjectFile(filePath)
const fileId = String(uploadResult && uploadResult.id ? uploadResult.id : '').trim()
if (!fileId) {
throw new Error('店铺主图上传失败:上传接口未返回文件ID')
}
this.setData({
'profileForm.coverImageFileId': fileId,
coverImagePreviewUrl: resolveUploadedImagePreviewUrl(uploadResult, filePath)
})
} catch (error) {
wx.showToast({ title: error.message || '店铺主图上传失败', icon: 'none' })
} finally {
this.setData({ coverUploading: false })
}
},
removeCoverImage() {
if (this.data.coverUploading || this.data.galleryUploading || this.data.saving) {
return
}
this.setData({
'profileForm.coverImageFileId': '',
coverImagePreviewUrl: ''
})
},
async chooseGalleryImages() {
if (this.data.galleryUploading || this.data.saving || this.data.coverUploading) {
return
}
const remainingCount = 9 - this.data.galleryItems.length
if (remainingCount <= 0) {
wx.showToast({ title: '最多上传 9 张环境照片', icon: 'none' })
return
}
try {
const filePaths = await chooseImageFilePaths(remainingCount)
if (!filePaths.length) {
return
}
this.setData({ galleryUploading: true })
const uploadedItems = []
for (let index = 0; index < filePaths.length; index += 1) {
const filePath = filePaths[index]
const uploadResult = await uploadObjectFile(filePath)
const fileId = String(uploadResult && uploadResult.id ? uploadResult.id : '').trim()
if (!fileId) {
throw new Error('环境照片上传失败:上传接口未返回文件ID')
}
uploadedItems.push({
fileId,
url: resolveUploadedImagePreviewUrl(uploadResult, filePath)
})
}
const galleryItems = this.data.galleryItems.concat(uploadedItems)
this.setData({
galleryItems,
'profileForm.galleryFileIds': galleryItems.map(item => item.fileId)
})
} catch (error) {
wx.showToast({ title: error.message || '环境照片上传失败', icon: 'none' })
} finally {
this.setData({ galleryUploading: false })
}
},
removeGalleryImage(event) {
if (this.data.galleryUploading || this.data.saving) {
return
}
const index = Number(event.currentTarget.dataset.index)
if (!Number.isInteger(index) || index < 0 || index >= this.data.galleryItems.length) {
wx.showToast({ title: '环境照片不存在', icon: 'none' })
return
}
const galleryItems = this.data.galleryItems.filter((item, itemIndex) => itemIndex !== index)
this.setData({
galleryItems,
'profileForm.galleryFileIds': galleryItems.map(item => item.fileId)
})
},
async saveProfileField() {
const shopName = String(this.data.profileForm.shopName || '').trim()
if (!shopName) {
wx.showToast({ title: '请填写店铺名称', icon: 'none' })
return
}
this.setData({ saving: true })
try {
await shopApi.saveSettings(buildProfilePayload(this.data.settingsSnapshot, this.data.profileForm))
wx.showToast({ title: '店铺信息已保存', icon: 'success' })
this.setData({ profileSheetVisible: false })
await this.loadSettings()
} catch (error) {
wx.showToast({ title: error.message || '店铺信息保存失败', icon: 'none' })
} finally {
this.setData({ saving: false })
}
},
editTags() {
wx.navigateTo({ url: '/pages/shop-tags/index' })
},
openScheduleSheet(event) {
this.setData({
scheduleSheetVisible: true,
activeScheduleTab: event.currentTarget.dataset.tab || 'RULE'
})
},
closeScheduleSheet() {
if (this.data.saving) {
return
}
this.setData({ scheduleSheetVisible: false })
},
stopPropagation() {},
switchScheduleTab(event) {
this.setData({ activeScheduleTab: event.currentTarget.dataset.tab || 'RULE' })
},
onInput(event) {
const field = event.currentTarget.dataset.field
this.setData({ [`form.${field}`]: event.detail.value })
},
selectPreset(event) {
const preset = buildPreset(event.currentTarget.dataset.value)
const form = {
...this.data.form,
schedulePresetType: preset.value,
scheduleWorkDays: copyWorkDays(preset.workDays),
startTime: preset.startTime,
endTime: preset.endTime
}
this.setData({
form,
presetOptions: buildPresetOptions(form.schedulePresetType),
weekdayOptions: buildWeekdayOptions(form.scheduleWorkDays)
})
},
toggleWeekday(event) {
const day = Number(event.currentTarget.dataset.value)
const workDays = copyWorkDays(this.data.form.scheduleWorkDays)
const nextDays = workDays.includes(day)
? workDays.filter(item => item !== day)
: [...workDays, day].sort()
this.setData({
'form.schedulePresetType': 'CUSTOM',
'form.scheduleWorkDays': nextDays,
presetOptions: buildPresetOptions('CUSTOM'),
weekdayOptions: buildWeekdayOptions(nextDays)
})
},
onStartChange(event) {
this.setData({
'form.startTime': event.detail.value,
'form.schedulePresetType': 'CUSTOM',
presetOptions: buildPresetOptions('CUSTOM')
})
},
onEndChange(event) {
this.setData({
'form.endTime': event.detail.value,
'form.schedulePresetType': 'CUSTOM',
presetOptions: buildPresetOptions('CUSTOM')
})
},
onExceptionInput(event) {
this.setData({ [`exceptionForm.${event.currentTarget.dataset.field}`]: event.detail.value })
},
onExceptionDateChange(event) {
this.setData({ 'exceptionForm.workDate': event.detail.value })
},
onExceptionStartChange(event) {
this.setData({ 'exceptionForm.startTime': event.detail.value })
},
onExceptionEndChange(event) {
this.setData({ 'exceptionForm.endTime': event.detail.value })
},
onExceptionTypeChange(event) {
const index = Number(event.detail.value)
const option = this.data.exceptionTypes[index] || this.data.exceptionTypes[0]
this.setData({
exceptionTypeIndex: index,
exceptionTypeLabel: exceptionTypeLabel(option.value),
'exceptionForm.exceptionType': option.value
})
},
async saveSchedule() {
const form = this.data.form
const workDays = copyWorkDays(form.scheduleWorkDays)
if (!workDays.length) {
wx.showToast({ title: '请选择营业日', icon: 'none' })
return
}
if (!form.startTime || !form.endTime || form.startTime >= form.endTime) {
wx.showToast({ title: '请填写正确的营业时间', icon: 'none' })
return
}
this.setData({ saving: true })
try {
await shopApi.saveSettings(buildShopPayload(this.data.settingsSnapshot, form))
markPlanningRefresh()
wx.showToast({ title: '排班已保存', icon: 'success' })
this.setData({ scheduleSheetVisible: false })
await this.loadSettings()
} catch (error) {
wx.showToast({ title: error.message || '排班保存失败', icon: 'none' })
} finally {
this.setData({ saving: false })
}
},
async saveException() {
const form = this.data.exceptionForm
if (!form.workDate || !form.exceptionType) {
wx.showToast({ title: '请补全特殊日期', icon: 'none' })
return
}
if (form.exceptionType !== 'REST' && (!form.startTime || !form.endTime || form.startTime >= form.endTime)) {
wx.showToast({ title: '请填写正确的特殊日期时间', icon: 'none' })
return
}
this.setData({ saving: true })
try {
await shopApi.saveScheduleException({
workDate: form.workDate,
exceptionType: form.exceptionType,
startTime: form.exceptionType === 'REST' ? null : form.startTime,
endTime: form.exceptionType === 'REST' ? null : form.endTime,
remark: String(form.remark || '').trim()
})
markPlanningRefresh()
wx.showToast({ title: '特殊日期已保存', icon: 'success' })
this.setData({ scheduleSheetVisible: false })
await this.loadSettings()
} catch (error) {
wx.showToast({ title: error.message || '特殊日期保存失败', icon: 'none' })
} finally {
this.setData({ saving: false })
}
},
back() {
wx.navigateBack()
}
})