const planningApi = require('../../api/planning') const dateUtil = require('../../utils/date') function canCreateAppointment() { const app = getApp() const userInfo = app.globalData.userInfo || {} return Number(userInfo.type) !== 3 } function resolveCalendarErrorMessage(error) { return error && error.message ? error.message : '规划数据加载失败' } 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}` } Page({ data: { viewMode: 'month', viewModes: [ { value: 'day', label: '日' }, { value: 'week', label: '周' }, { value: 'month', 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: '10:00', businessEndTime: '22:00', artists: [], appointments: [], daySummaries: [], monthDays: [], weekDays: [], dayLanes: [], hours: [], timelineHeight: 720, laneWidth: 720, laneItemWidth: 240, laneHeaderHeight: 54, dayTotal: 0, freeArtistCount: 0, pendingCount: 0, canCreateAppointment: true, loading: false, calendarError: '' }, onLoad() { this.setData({ canCreateAppointment: canCreateAppointment() }) 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() } }, switchView(event) { this.setData({ viewMode: event.currentTarget.dataset.mode }) this.prepareView() this.loadCalendar() }, switchMonthDisplay(event) { this.setData({ monthDisplayMode: event.currentTarget.dataset.mode }) }, 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.prepareView() }, selectDate(event) { const currentDate = dateUtil.formatDate(event.currentTarget.dataset.date) this.setData({ currentDate, currentDateText: currentDate, viewMode: this.data.viewMode === 'month' ? 'day' : this.data.viewMode }) 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() this.setData({ loading: true }) try { const data = await planningApi.calendar({ startDate: range.start, endDate: range.end, artistId: this.data.selectedArtistId || undefined }) this.applyCalendar(data) this.setData({ calendarError: '' }) } catch (error) { this.clearCalendarView() this.setData({ calendarError: resolveCalendarErrorMessage(error), selectedArtistId: '', selectedArtistName: '全部员工' }) wx.showToast({ title: '规划数据加载失败', icon: 'none' }) } finally { this.setData({ loading: false }) } }, clearCalendarView() { this.setData({ businessStartTime: '10:00', businessEndTime: '22:00', artists: [], appointments: [], daySummaries: [], monthDays: [], weekDays: [], dayLanes: [], hours: [], dayTotal: 0, freeArtistCount: 0, pendingCount: 0 }) }, 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 artists = calendar.artists || [] this.setData({ businessStartTime: (calendar.businessStartTime || '10:00').slice(0, 5), businessEndTime: (calendar.businessEndTime || '22:00').slice(0, 5), artists, appointments: calendar.appointments || [], daySummaries: calendar.daySummaries || [] }) this.prepareView() }, prepareView() { 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) this.setData({ dateTitle: title, rangeText: this.data.viewMode === 'month' ? '月视图' : this.data.viewMode === 'week' ? '周视图' : '日视图', weekRange: `${formatMonthDay(range.start)} - ${formatMonthDay(range.end)}`, monthDays: this.buildMonthDays(), weekDays: this.buildWeekDays(), ...this.buildDayView() }) }, buildMonthDays() { const summaryMap = this.summaryMap() const todayText = dateUtil.formatDate(new Date()) const artistTemplate = this.data.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 artistCounts = this.normalizeArtistCounts(summary.artistCounts || artistTemplate) return { ...day, isPast: day.date < todayText, totalCount: summary.totalCount || 0, dayStatus: summary.dayStatus || 'free', artistCounts, expandedBlocks: this.buildExpandedBlocks(artistCounts), rowBlocks: this.buildRowBlocks(artistCounts) } }) }, buildWeekDays() { const start = dateUtil.startOfWeek(this.data.currentDateText) const summaryMap = this.summaryMap() return 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 artistCounts = this.normalizeArtistCounts(summary.artistCounts || []).filter(count => count.count > 0) return { date, weekName: `周${label}`, day: target.getDate(), totalCount: summary.totalCount || 0, artistCounts: artistCounts.map(count => ({ ...count, width: Math.max(12, Math.min(100, count.count * 22)), barWidth: Math.max(14, Math.min(100, count.count * 18)) })) } }) }, buildDayView() { const startMinute = dateUtil.minutesOfDay(this.data.businessStartTime) const endMinute = dateUtil.minutesOfDay(this.data.businessEndTime) const timelineHeight = Math.max(560, endMinute - startMinute) const laneHeaderHeight = 54 const hours = [] for (let cursor = startMinute; cursor <= endMinute; cursor += 60) { hours.push({ value: cursor, label: dateUtil.timeFromMinutes(cursor), top: cursor - startMinute + laneHeaderHeight }) } const filteredArtists = this.data.selectedArtistId ? this.data.artists.filter(item => String(item.id) === String(this.data.selectedArtistId)) : this.data.artists const dayAppointments = this.data.appointments.filter(item => resolveAppointmentDate(item) === this.data.currentDateText) const lanes = filteredArtists.map(artist => { const blocks = dayAppointments .filter(item => String(item.artistId) === String(artist.id)) .map(item => { const itemStart = resolveAppointmentStartMinute(item) return { ...item, top: Math.max(0, itemStart - startMinute) + laneHeaderHeight, height: Math.max(64, item.durationMinutes || 60), timeText: resolveAppointmentTimeText(item) } }) return { ...artist, blocks } }) const pendingCount = dayAppointments.filter(item => item.status === 0).length return { dayLanes: lanes, hours, timelineHeight: timelineHeight + laneHeaderHeight, laneHeaderHeight, laneItemWidth: 248, laneWidth: Math.max(720, lanes.length * 248), dayTotal: dayAppointments.length, freeArtistCount: lanes.filter(item => item.blocks.length === 0).length, pendingCount } }, summaryMap() { return (this.data.daySummaries || []).reduce((map, item) => { map[item.date] = item return map }, {}) }, normalizeArtistCounts(counts) { const colorMap = this.data.artists.reduce((map, artist) => { map[artist.id] = artist return map }, {}) return (counts || []).map(count => { const artist = colorMap[count.artistId] || {} return { ...count, color: count.color || artist.color || '#B8B0A6', shortName: count.shortName || artist.shortName || '?', 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 } wx.navigateTo({ url: `/pages/appointment-form/index?date=${this.data.currentDateText}&artistId=${this.data.selectedArtistId || ''}` }) }, openAppointment(event) { wx.navigateTo({ url: `/pages/appointment-detail/index?id=${event.currentTarget.dataset.id}` }) } })