const planningApi = require('../../api/planning') const dateUtil = require('../../utils/date') const userApi = require('../../api/user') const auth = require('../../utils/auth') const { uploadProfileImage } = require('../../utils/upload') const { normalizeAvatar } = require('../../utils/profile-card') const profileCache = require('../../utils/profile-cache') const employeesApi = require('../../api/employees') const { showErrorToast, toUserMessage } = require('../../utils/toast') function canCreateAppointment() { const app = getApp() const userInfo = app.globalData.userInfo || {} return Number(userInfo.type) !== 3 } function resolveCalendarErrorMessage(error) { return toUserMessage(error, '日程数据加载失败') } const LANE_TINTS = ['#EAF3FA', '#FBF1EB', '#EEF5EF'] const DESIGN_ARTIST_COLORS = { 张小雨: '#43789E', 林小满: '#96684B', 陈小桃: '#587959' } const LEGACY_ARTIST_COLORS = { '#7BA7C7': '#43789E', '#D7A86E': '#96684B', '#8FB89A': '#587959' } function resolveDisplayColor(artist = {}, fallback) { const name = String(artist.nickname || artist.name || artist.artistName || '') const matchedName = Object.keys(DESIGN_ARTIST_COLORS).find(key => name.includes(key)) if (matchedName) return DESIGN_ARTIST_COLORS[matchedName] const color = String(artist.color || fallback || '') return LEGACY_ARTIST_COLORS[color.toUpperCase()] || color || '#B8B0A6' } function buildWeekSegments(artistCounts) { const counts = (artistCounts || []).map(count => ({ ...count, width: Math.round(count.count * 75.2) })) const usable = 396 - Math.max(0, counts.length - 1) * 4 const rawTotal = counts.reduce((total, count) => total + count.width, 0) if (rawTotal <= usable || rawTotal === 0) return counts const scale = usable / rawTotal return counts.map(count => ({ ...count, width: Math.max(8, Math.floor(count.width * scale)) })) } function toLocalDate(value) { return value instanceof Date ? new Date(value.getTime()) : new Date(String(value).replace(/-/g, '/')) } function formatMonthDay(value) { const target = toLocalDate(value) return `${target.getMonth() + 1}月${target.getDate()}日` } function resolveAppointmentDate(item) { if (item.date) return item.date return String(item.startTime || '').slice(0, 10) } function resolveAppointmentStartMinute(item) { if (item.startMinute !== undefined && item.startMinute !== null) { return Number(item.startMinute) } const timeText = String(item.startTime || '').slice(11, 16) return dateUtil.minutesOfDay(timeText) } function resolveAppointmentTimeText(item) { const startMinute = resolveAppointmentStartMinute(item) const duration = Number(item.durationMinutes || 60) const startText = String(item.startTime || '').slice(11, 16) || dateUtil.timeFromMinutes(startMinute) const endText = String(item.endTime || '').slice(11, 16) || dateUtil.timeFromMinutes(startMinute + duration) return `${startText}-${endText}` } function normalizeTime(value) { const match = /^(\d{1,2}):(\d{2})(?::\d{2})?$/.exec(String(value || '').trim()) if (!match) return '' const hour = Number(match[1]) const minute = Number(match[2]) if (hour > 23 || minute > 59) return '' return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}` } function resolveBusinessHours(calendar = {}, targetDate) { const day = targetDate && (calendar.daySummaries || []).find(item => item.date === targetDate) if (day) { if (day.shopOpen === false) return null const dayStart = normalizeTime(day.shopStartTime) const dayEnd = normalizeTime(day.shopEndTime) if (dayStart && dayEnd && dateUtil.minutesOfDay(dayEnd) > dateUtil.minutesOfDay(dayStart)) return { start: dayStart, end: dayEnd } } const parts = String(calendar.businessHours || '').split('-') const start = normalizeTime(calendar.businessStartTime || parts[0]) const end = normalizeTime(calendar.businessEndTime || parts[1]) if (!start || !end || dateUtil.minutesOfDay(end) <= dateUtil.minutesOfDay(start)) return null return { start, end } } function hasBusinessHours(calendar = {}) { const summaries = Array.isArray(calendar.daySummaries) ? calendar.daySummaries : [] if (summaries.length) { return summaries.some(day => day.shopOpen !== false && Boolean(resolveBusinessHours(calendar, day.date))) } return Boolean(resolveBusinessHours(calendar)) } function layoutAppointmentBlocks(items, startMinute, minuteScale, laneHeaderHeight, defaultLaneWidth) { const entries = (items || []) .filter(item => item.startTime) .map(item => { const itemStart = resolveAppointmentStartMinute(item) const requestedDuration = Number(item.durationMinutes || 60) const duration = Math.max(15, Number.isFinite(requestedDuration) ? requestedDuration : 60) return { ...item, itemStart, itemEnd: itemStart + duration, durationMinutes: duration } }) .sort((left, right) => left.itemStart - right.itemStart || left.itemEnd - right.itemEnd) const groups = [] entries.forEach(entry => { let group = groups[groups.length - 1] if (!group || entry.itemStart >= group.end) { group = { entries: [], end: entry.itemEnd, columnCount: 0 } groups.push(group) } group.entries.push(entry) group.end = Math.max(group.end, entry.itemEnd) }) let maxColumns = 1 groups.forEach(group => { const columnEnds = [] group.entries.forEach(entry => { let columnIndex = columnEnds.findIndex(end => end <= entry.itemStart) if (columnIndex < 0) columnIndex = columnEnds.length columnEnds[columnIndex] = entry.itemEnd entry.columnIndex = columnIndex }) group.columnCount = columnEnds.length group.entries.forEach(entry => { entry.columnCount = group.columnCount }) maxColumns = Math.max(maxColumns, group.columnCount) }) const laneWidth = Math.max(defaultLaneWidth, maxColumns * defaultLaneWidth) const blocks = entries.map(entry => { const slotWidth = laneWidth / entry.columnCount return { ...entry, top: Math.max(0, entry.itemStart - startMinute) * minuteScale + laneHeaderHeight, height: Math.max(40, entry.durationMinutes * minuteScale), left: Math.round(entry.columnIndex * slotWidth + 12), width: Math.round(slotWidth - 24), compact: entry.durationMinutes <= 15, overlapCount: entry.columnCount, timeText: resolveAppointmentTimeText(entry) } }) return { blocks, laneWidth } } Page({ data: { viewMode: 'month', viewModes: [ { value: 'month', label: '月' }, { value: 'week', label: '周' }, { value: 'day', label: '日' } ], monthDisplayMode: 'count', monthDisplayModes: [ { value: 'count', label: '单量' }, { value: 'blocks', label: '点阵' }, { value: 'rows', label: '横条' } ], monthRowLabelVisible: false, weekLabels: ['一', '二', '三', '四', '五', '六', '日'], currentDate: new Date(), currentDateText: dateUtil.formatDate(new Date()), selectedArtistId: '', selectedArtistName: '全部美甲师', dateTitle: '', rangeText: '', weekRange: '', businessStartTime: '', businessEndTime: '', businessHoursConfigured: false, businessHoursText: '营业时间未设置', artists: [], monthDays: [], weekDays: [], weekTotalCount: 0, weekUnassignedTotal: 0, weekLegend: [], todayText: dateUtil.formatDate(new Date()), dayLanes: [], hours: [], hasTimedAppointments: false, timelineHeight: 720, timelineViewportHeight: 720, laneWidth: 720, laneItemWidth: 240, laneHeaderHeight: 54, dayTotal: 0, freeArtistCount: 0, pendingCount: 0, unassignedCount: 0, historicalBackfillItems: [], rangeUnassignedCount: 0, nearestUnassignedDate: '', canCreateAppointment: true, canManageShopSettings: false, loading: false, calendarError: '', phoneBannerVisible: false, profilePromptVisible: false, profileSaving: false, profileForm: { nickname: '', avatar: '', avatarFileId: '' } }, onLoad() { const userInfo = getApp().globalData.userInfo || {} this.setData({ canCreateAppointment: canCreateAppointment(), canManageShopSettings: Number(userInfo.type) === 2 }) this.loadCalendar() }, onShow() { const app = getApp() const storageRefresh = wx.getStorageSync('planningNeedRefresh') === '1' if (this._needRefresh || app.globalData.planningNeedRefresh || storageRefresh) { this._needRefresh = false app.globalData.planningNeedRefresh = false wx.removeStorageSync('planningNeedRefresh') this.loadCalendar() } if (this._refreshCalendarOnShow) { this._refreshCalendarOnShow = false this.loadCalendar() } this.refreshAccountPrompts() }, async refreshAccountPrompts() { let shouldShowProfilePrompt = false try { const profile = await profileCache.getProfile() const session = auth.getSession() getApp().setSession({ ...session, userInfo: { ...(session.userInfo || {}), ...profile } }) const today = dateUtil.formatDate(new Date()) const dismissed = wx.getStorageSync(auth.PHONE_BANNER_DISMISSED_KEY) const missingNickname = !String(profile.nickname || '').trim() || String(profile.nickname).startsWith('微信用户') const avatar = normalizeAvatar(profile.avatar) const skipped = wx.getStorageSync(auth.PROFILE_PROMPT_SKIPPED_KEY) === '1' shouldShowProfilePrompt = !skipped && (missingNickname || !avatar) this.setData({ phoneBannerVisible: Number(profile.phoneVerified) !== 1 && dismissed !== today, profilePromptVisible: false, profileForm: { nickname: missingNickname ? '' : profile.nickname, avatar, avatarFileId: '' } }) } catch (error) { // 资料提醒失败不影响日程数据。 } const navigatedToReview = await this.showEmployeeReviewNotice() if (!navigatedToReview) { this.setData({ profilePromptVisible: shouldShowProfilePrompt }) } }, async showEmployeeReviewNotice() { const app = getApp() const userInfo = app.globalData.userInfo || {} if (Number(userInfo.type) !== 2 || app.globalData.reviewNoticeShown) return false let summary try { summary = await employeesApi.reviewSummary() } catch (error) { return false } if (!summary.noticeEnabled || Number(summary.pendingCount || 0) <= 0) return false app.globalData.reviewNoticeShown = true const result = await new Promise(resolve => { wx.showModal({ title: '有美甲师申请待审核', content: `当前有 ${summary.pendingCount} 条美甲师加入申请,请在小程序员工页面审核。是否立即处理?`, cancelText: '稍后处理', confirmText: '立即审核', success: resolve, fail: () => resolve({ confirm: false }) }) }) if (!result.confirm) return false app.globalData.openEmployeeReview = true wx.switchTab({ url: '/pages/employees/index' }) return true }, openAccountSettings() { wx.navigateTo({ url: '/pages/account-settings/index' }) }, dismissPhoneBanner() { wx.setStorageSync(auth.PHONE_BANNER_DISMISSED_KEY, dateUtil.formatDate(new Date())) this.setData({ phoneBannerVisible: false }) }, onNicknameInput(event) { this.setData({ 'profileForm.nickname': event.detail.value }) }, async chooseWechatAvatar(event) { const filePath = event.detail && event.detail.avatarUrl if (!filePath) return this.setData({ profileSaving: true }) try { const uploaded = await uploadProfileImage(filePath) this.setData({ 'profileForm.avatar': filePath, 'profileForm.avatarFileId': uploaded && uploaded.fileId ? String(uploaded.fileId) : '' }) } catch (error) { showErrorToast(error, '头像上传失败') } finally { this.setData({ profileSaving: false }) } }, skipProfilePrompt() { wx.setStorageSync(auth.PROFILE_PROMPT_SKIPPED_KEY, '1') this.setData({ profilePromptVisible: false }) }, async saveWechatProfile() { const nickname = String(this.data.profileForm.nickname || '').trim() if (!nickname || !this.data.profileForm.avatar) { wx.showToast({ title: '请选择头像并填写昵称', icon: 'none' }); return } this.setData({ profileSaving: true }) try { await userApi.updateInfo({ nickname, avatarFileId: this.data.profileForm.avatarFileId || undefined }) profileCache.invalidate() this.setData({ profilePromptVisible: false }) wx.showToast({ title: '资料已保存', duration: 3000 }) } catch (error) { showErrorToast(error, '资料保存失败', { duration: 3000 }) } finally { this.setData({ profileSaving: false }) } }, switchView(event) { this.setData({ viewMode: event.currentTarget.dataset.mode }) this.loadCalendar() }, switchMonthDisplay(event) { this.setData({ monthDisplayMode: event.currentTarget.dataset.mode }) this.prepareView() }, toggleMonthRowLabel() { this.setData({ monthRowLabelVisible: !this.data.monthRowLabelVisible }) }, selectArtist(event) { const id = event.currentTarget.dataset.id || '' const artist = this.data.artists.find(item => String(item.id) === String(id)) this.setData({ selectedArtistId: id, selectedArtistName: artist ? artist.name : '全部美甲师' }) this.loadCalendar() }, selectMonthDate(event) { const appointmentDate = dateUtil.formatDate(event.currentTarget.dataset.date) const target = toLocalDate(appointmentDate) this.setData({ viewMode: 'day', currentDate: target, currentDateText: appointmentDate }) this.loadCalendar() }, onProfileAvatarError() { this.setData({ 'profileForm.avatar': '' }) }, selectWeekDate(event) { const appointmentDate = dateUtil.formatDate(event.currentTarget.dataset.date) const target = toLocalDate(appointmentDate) this.setData({ currentDate: target, currentDateText: appointmentDate }) this.prepareView() }, prevRange() { this.shiftRange(-1) }, nextRange() { this.shiftRange(1) }, goToday() { const today = new Date() this.setData({ currentDate: today, currentDateText: dateUtil.formatDate(today) }) this.loadCalendar() }, shiftRange(direction) { let next if (this.data.viewMode === 'month') { next = dateUtil.addMonths(this.data.currentDateText, direction) } else if (this.data.viewMode === 'week') { next = dateUtil.addDays(this.data.currentDateText, direction * 7) } else { next = dateUtil.addDays(this.data.currentDateText, direction) } this.setData({ currentDate: next, currentDateText: dateUtil.formatDate(next) }) this.loadCalendar() }, async loadCalendar() { const range = this.resolveRange() const requestKey = `${range.start}|${range.end}|${this.data.selectedArtistId || ''}` if (this._calendarInflight && this._calendarInflight.key === requestKey) { return this._calendarInflight.promise } const requestId = (this._calendarRequestId || 0) + 1 this._calendarRequestId = requestId this.setData({ loading: true }) const promise = planningApi.calendar({ startDate: range.start, endDate: range.end, artistId: this.data.selectedArtistId || undefined }).then(data => { if (requestId !== this._calendarRequestId) return this.applyCalendar(data) }).catch(error => { if (requestId !== this._calendarRequestId) return this.clearCalendarView() this.setData({ calendarError: resolveCalendarErrorMessage(error), selectedArtistId: '', selectedArtistName: '全部美甲师' }) wx.showToast({ title: '日程数据加载失败', icon: 'none' }) }).finally(() => { if (requestId === this._calendarRequestId) this.setData({ loading: false }) if (this._calendarInflight && this._calendarInflight.promise === promise) { this._calendarInflight = null } }) this._calendarInflight = { key: requestKey, promise } return promise }, clearCalendarView() { this._calendarData = { artists: [], appointments: [], daySummaries: [] } this.setData({ businessStartTime: '', businessEndTime: '', businessHoursConfigured: false, businessHoursText: '营业时间暂不可用', artists: [], monthDays: [], weekDays: [], weekTotalCount: 0, weekUnassignedTotal: 0, weekLegend: [], dayLanes: [], hours: [], hasTimedAppointments: false, dayTotal: 0, freeArtistCount: 0, pendingCount: 0, unassignedCount: 0, rangeUnassignedCount: 0, nearestUnassignedDate: '' }) }, resolveRange() { const current = this.data.currentDateText if (this.data.viewMode === 'week') { return { start: dateUtil.formatDate(dateUtil.startOfWeek(current)), end: dateUtil.formatDate(dateUtil.endOfWeek(current)) } } if (this.data.viewMode === 'month') { return { start: dateUtil.formatDate(dateUtil.startOfMonth(current)), end: dateUtil.formatDate(dateUtil.endOfMonth(current)) } } return { start: current, end: current } }, applyCalendar(calendar) { const businessHours = resolveBusinessHours(calendar) const snapshot = { businessStartTime: businessHours ? businessHours.start : '', businessEndTime: businessHours ? businessHours.end : '', businessHoursConfigured: hasBusinessHours(calendar), artists: (Array.isArray(calendar.artists) ? calendar.artists : []).map(artist => ({ ...artist, color: resolveDisplayColor({ name: artist.name || artist.nickname, color: artist.color }) })), appointments: Array.isArray(calendar.appointments) ? calendar.appointments : [], daySummaries: Array.isArray(calendar.daySummaries) ? calendar.daySummaries : [] } this._calendarData = snapshot this.setData({ businessStartTime: snapshot.businessStartTime, businessEndTime: snapshot.businessEndTime, businessHoursConfigured: snapshot.businessHoursConfigured, artists: snapshot.artists, calendarError: '', rangeUnassignedCount: snapshot.appointments.filter(item => !item.artistId).length, nearestUnassignedDate: this.findNearestUnassignedDate(snapshot.appointments), ...this.buildViewState(snapshot) }) }, prepareView() { this.setData(this.buildViewState(this._calendarData)) }, buildViewState(calendar = {}) { const current = this.data.currentDateText const range = this.resolveRange() const title = this.data.viewMode === 'month' ? dateUtil.formatMonth(current) : this.data.viewMode === 'week' ? `${formatMonthDay(range.start)} - ${formatMonthDay(range.end)}` : dateUtil.formatCnDate(current) const state = { dateTitle: title, rangeText: this.data.viewMode === 'month' ? '月视图' : this.data.viewMode === 'week' ? '周视图' : '日视图', weekRange: `${formatMonthDay(range.start)} - ${formatMonthDay(range.end)}`, businessHoursConfigured: hasBusinessHours(calendar), currentShopOpen: true, businessHoursText: '营业时间暂不可用', monthDays: [], weekDays: [], dayLanes: [], hours: [] } const daySummary = this.summaryMap(calendar)[current] const dailyHours = resolveBusinessHours(calendar, current) state.currentShopOpen = !daySummary || daySummary.shopOpen !== false state.businessHoursText = !state.currentShopOpen ? '门店休息' : dailyHours ? `${dailyHours.start}-${dailyHours.end}` : '营业时间暂不可用' if (this.data.viewMode === 'month') { state.monthDays = this.buildMonthDays(calendar) return state } if (this.data.viewMode === 'week') { const weekDays = this.buildWeekDays(calendar) const legendMap = {} weekDays.forEach(day => { day.artistCounts.forEach(count => { if (!count.artistId || count.artistId === '__unassigned__' || legendMap[count.artistId]) return legendMap[count.artistId] = { artistId: count.artistId, name: count.artistName || count.shortName || '?', color: count.color } }) }) state.weekDays = weekDays state.weekTotalCount = weekDays.reduce((total, day) => total + Number(day.totalCount || 0), 0) state.weekUnassignedTotal = weekDays.reduce((total, day) => total + Number(day.unassignedCount || 0), 0) state.weekLegend = Object.keys(legendMap).map(key => legendMap[key]) return state } return { ...state, ...this.buildDayView(calendar) } }, buildMonthDays(calendar) { const summaryMap = this.summaryMap(calendar) const todayText = dateUtil.formatDate(new Date()) const artistTemplate = (calendar.artists || []).map(artist => ({ artistId: artist.id, artistName: artist.name, shortName: artist.shortName, color: artist.color, count: 0, status: 'free' })) return dateUtil.monthGrid(this.data.currentDateText).map(day => { const summary = summaryMap[day.date] || {} const unassignedCount = Number(summary.unassignedCount || 0) const artistCounts = this.withUnassignedCount( this.normalizeArtistCounts(summary.artistCounts || artistTemplate, calendar), unassignedCount ) return { ...day, isPast: day.date < todayText, totalCount: summary.totalCount || 0, unassignedCount, dayStatus: this.resolveDisplayStatus(summary, artistCounts), artistCounts, expandedBlocks: this.data.monthDisplayMode === 'blocks' ? this.buildExpandedBlocks(artistCounts) : [], rowBlocks: this.data.monthDisplayMode === 'rows' ? this.buildRowBlocks(artistCounts) : [] } }) }, buildWeekDays(calendar) { const start = dateUtil.startOfWeek(this.data.currentDateText) const summaryMap = this.summaryMap(calendar) const days = this.data.weekLabels.map((label, index) => { const target = dateUtil.addDays(start, index) const date = dateUtil.formatDate(target) const summary = summaryMap[date] || { artistCounts: [], totalCount: 0 } const unassignedCount = Number(summary.unassignedCount || 0) const artistCounts = this.normalizeArtistCounts(summary.artistCounts || [], calendar) .filter(count => count.count > 0 && count.artistId !== '__unassigned__') return { date, weekName: `周${label}`, day: target.getDate(), totalCount: summary.totalCount || 0, unassignedCount, shopOpen: summary.shopOpen !== false, statusText: this.resolveDisplayStatus(summary, artistCounts) === 'rest' ? '休' : '营业', artistCounts: buildWeekSegments(artistCounts) } }) return days }, buildDayView(calendar) { const minuteScale = 2.5 const daySummary = this.summaryMap(calendar)[this.data.currentDateText] || null const businessHours = resolveBusinessHours(calendar, this.data.currentDateText) const filteredArtists = this.data.selectedArtistId ? (calendar.artists || []).filter(item => String(item.id) === String(this.data.selectedArtistId)) : (calendar.artists || []) const dayAppointments = (calendar.appointments || []).filter(item => resolveAppointmentDate(item) === this.data.currentDateText) const historicalBackfillItems = dayAppointments.filter(item => item.historicalBackfill) const timedAppointments = dayAppointments .filter(item => item.startTime) .filter(item => !this.data.selectedArtistId || String(item.artistId) === String(this.data.selectedArtistId)) const startMinutes = timedAppointments .map(resolveAppointmentStartMinute) .filter(value => Number.isFinite(value) && value >= 0 && value < 1440) if (!businessHours && !startMinutes.length) { const pendingCount = dayAppointments.filter(item => item.status === 0).length return { dayLanes: [], hours: [], hasTimedAppointments: false, timelineHeight: 0, timelineViewportHeight: 320, laneHeaderHeight: 54, laneItemWidth: 248, laneWidth: 720, dayTotal: dayAppointments.length, freeArtistCount: 0, pendingCount, unassignedCount: dayAppointments.filter(item => !item.artistId).length, shopClosed: Boolean(daySummary && daySummary.shopOpen === false), historicalBackfillItems } } const startMinute = businessHours ? dateUtil.minutesOfDay(businessHours.start) : Math.floor(Math.min(...startMinutes) / 60) * 60 const latestAppointmentEnd = timedAppointments.reduce((latest, item) => { const start = resolveAppointmentStartMinute(item) const duration = Number(item.durationMinutes || 60) return Math.max(latest, start + (Number.isFinite(duration) ? duration : 60)) }, startMinute) const endMinute = businessHours ? dateUtil.minutesOfDay(businessHours.end) : Math.min(1440, Math.max(startMinute + 60, Math.ceil(latestAppointmentEnd / 60) * 60)) const timelineHeight = (endMinute - startMinute) * minuteScale const laneHeaderHeight = 54 const hours = [] for (let cursor = startMinute; cursor <= endMinute; cursor += 60) { hours.push({ value: cursor, label: dateUtil.timeFromMinutes(cursor), top: (cursor - startMinute) * minuteScale + laneHeaderHeight }) } const employeeLanes = filteredArtists.map((artist, artistIndex) => { const tint = LANE_TINTS[artistIndex % LANE_TINTS.length] const blocks = dayAppointments .filter(item => String(item.artistId) === String(artist.id)) .filter(item => item.startTime) .map(item => { const itemStart = resolveAppointmentStartMinute(item) return { ...item, top: Math.max(0, itemStart - startMinute) * minuteScale + laneHeaderHeight, height: Math.max(40, (item.durationMinutes || 60) * minuteScale), left: 12, width: 224, compact: Number(item.durationMinutes || 60) <= 15, timeText: resolveAppointmentTimeText(item), tint } }) return { ...artist, artistId: artist.id, blocks, width: 248 } }) const unassignedLayout = layoutAppointmentBlocks( dayAppointments.filter(item => !item.artistId), startMinute, minuteScale, laneHeaderHeight, 248 ) const unassignedBlocks = unassignedLayout.blocks.map(block => ({ ...block, tint: '#FFF3E7' })) const lanes = this.data.selectedArtistId ? employeeLanes : [{ id: '__unassigned__', artistId: '__unassigned__', name: '待分配', color: '#D59A52', blocks: unassignedBlocks, width: unassignedLayout.laneWidth, isUnassigned: true, emptyText: '暂无待分配' }, ...employeeLanes] const pendingCount = dayAppointments.filter(item => item.status === 0).length return { dayLanes: lanes, hours, hasTimedAppointments: timedAppointments.length > 0, timelineHeight: timelineHeight + laneHeaderHeight, timelineViewportHeight: Math.min(820, timelineHeight + laneHeaderHeight), laneHeaderHeight, laneItemWidth: 248, laneWidth: Math.max(720, lanes.reduce((width, lane) => width + (lane.width || 248), 0)), dayTotal: dayAppointments.length, freeArtistCount: employeeLanes.filter(item => item.blocks.every(block => block.historicalBackfill)).length, pendingCount, unassignedCount: unassignedBlocks.length, shopClosed: Boolean(daySummary && daySummary.shopOpen === false), historicalBackfillItems } }, resolveDisplayStatus(summary = {}, artistCounts = []) { if (summary.shopOpen === false || summary.dayStatus === 'rest') return 'rest' if (this.data.selectedArtistId) { const selected = artistCounts.find(item => String(item.artistId) === String(this.data.selectedArtistId)) return selected ? selected.status : 'rest' } return summary.dayStatus === 'full' ? 'full' : 'working' }, withUnassignedCount(artistCounts, unassignedCount) { if (!unassignedCount) return artistCounts return [{ artistId: '__unassigned__', artistName: '待分配', shortName: '待', color: '#D59A52', count: unassignedCount, status: 'pending' }, ...(artistCounts || [])] }, findNearestUnassignedDate(appointments) { const dates = (appointments || []) .filter(item => !item.artistId) .map(resolveAppointmentDate) .filter(Boolean) .sort() if (!dates.length) return '' const today = dateUtil.formatDate(new Date()) return dates.find(date => date >= today) || dates[0] }, openNearestUnassigned() { if (!this.data.nearestUnassignedDate) return const target = this.data.nearestUnassignedDate this.setData({ viewMode: 'day', currentDate: toLocalDate(target), currentDateText: target, selectedArtistId: '', selectedArtistName: '全部美甲师' }) this.loadCalendar() }, summaryMap(calendar) { return (calendar.daySummaries || []).reduce((map, item) => { map[item.date] = item return map }, {}) }, normalizeArtistCounts(counts, calendar) { const colorMap = (calendar.artists || []).reduce((map, artist) => { map[artist.id] = artist return map }, {}) return (counts || []).map(count => { const artist = colorMap[count.artistId] || {} const artistName = count.artistName || artist.name || artist.nickname || '' return { ...count, color: resolveDisplayColor({ name: artistName, color: count.color || artist.color }), shortName: count.shortName || artist.shortName || '?', artistName, count: Number(count.count || 0) } }) }, buildExpandedBlocks(artistCounts) { return (artistCounts || []).reduce((blocks, count) => { for (let index = 0; index < Number(count.count || 0); index += 1) { blocks.push({ key: `${count.artistId || count.shortName}-${index}`, artistId: count.artistId, color: count.color, shortName: count.shortName }) } return blocks }, []) }, buildRowBlocks(artistCounts) { return (artistCounts || []).reduce((rows, count) => { for (let index = 0; index < Number(count.count || 0); index += 1) { rows.push({ key: `${count.artistId || count.shortName}-row-${index}`, artistId: count.artistId, color: count.color, shortName: count.shortName, artistName: count.artistName || count.shortName }) } return rows }, []) }, createAppointment() { if (!this.data.canCreateAppointment) { wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' }) return } if (!this.data.businessHoursConfigured) { wx.showToast({ title: '请先在店铺设置中配置营业时间', icon: 'none' }) return } if (this.data.viewMode === 'day' && this.data.currentShopOpen === false) { wx.showToast({ title: '该日期门店休息,不能新建普通预约', icon: 'none' }) return } this.openAppointmentForm(this.data.viewMode === 'day' ? this.data.currentDateText : '') }, openBackfillOrder(serviceDate) { if (!this.data.canCreateAppointment) { wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' }) return } const query = [`serviceDate=${encodeURIComponent(serviceDate || this.data.currentDateText)}`] if (this.data.selectedArtistId) { query.push(`artistId=${encodeURIComponent(this.data.selectedArtistId)}`) } wx.navigateTo({ url: `/pages/backfill-order/index?${query.join('&')}` }) }, openAppointmentForm(appointmentDate) { const query = [] if (appointmentDate) { query.push(`date=${encodeURIComponent(appointmentDate)}`) } else { query.push('dateMode=manual') } if (this.data.selectedArtistId) { query.push(`artistId=${encodeURIComponent(this.data.selectedArtistId)}`) } const queryText = query.length ? `?${query.join('&')}` : '' wx.navigateTo({ url: `/pages/appointment-form/index${queryText}` }) }, openShopSettings() { this._refreshCalendarOnShow = true wx.navigateTo({ url: '/pages/shop-settings/index' }) }, openAppointment(event) { wx.navigateTo({ url: `/pages/appointment-detail/index?id=${event.currentTarget.dataset.id}` }) }, stopTap() { }, async quickUpdateStatus(event) { const appointment = (this._calendarData && this._calendarData.appointments || []).find(item => String(item.orderItemId) === String(event.currentTarget.dataset.id)) if (!appointment) return try { await planningApi.updateStatus(appointment.orderId, Number(event.currentTarget.dataset.status)) wx.showToast({ title: Number(event.currentTarget.dataset.status) === 2 ? '补单已完成' : '预约已确认', icon: 'success' }) this.loadCalendar() } catch (error) { showErrorToast(error, '预约状态更新失败') } }, quickTransfer(event) { wx.navigateTo({ url: `/pages/artist-transfer/index?id=${event.currentTarget.dataset.id}` }) }, quickCancel(event) { const appointment = (this._calendarData && this._calendarData.appointments || []).find(item => String(item.orderItemId) === String(event.currentTarget.dataset.id)) if (!appointment) return wx.showModal({ title: '取消预约', editable: true, placeholderText: '可填写取消原因', content: '', confirmText: '确认取消', success: result => { if (result.confirm) { this.updateAppointmentStatus(appointment.orderId, 3, result.content || '') } } }) }, async updateAppointmentStatus(orderId, status, cancelReason) { try { await planningApi.updateStatus(orderId, status, cancelReason) wx.showToast({ title: '预约已取消', icon: 'success' }) this.loadCalendar() } catch (error) { showErrorToast(error, '预约取消失败') } } })