Files
JayuCloud/FingertipManager-Program/pages/planning/index.js

360 lines
11 KiB
JavaScript

const planningApi = require('../../api/planning')
const dateUtil = require('../../utils/date')
const config = require('../../utils/config')
const mock = require('../../utils/mock')
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,
dayTotal: 0,
freeArtistCount: 0,
pendingCount: 0,
loading: false,
loadError: false,
errorMessage: ''
},
onLoad() {
this.loadCalendar()
},
onShow() {
if (this._needRefresh) {
this._needRefresh = false
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.setData({ loadError: false, errorMessage: '' })
this.applyCalendar(data)
} catch (error) {
if (config.USE_DEV_MOCK_DATA) {
this.setData({ loadError: false, errorMessage: '' })
this.applyCalendar(mock.buildCalendar(this.data.currentDateText))
} else {
this.setData({
loadError: true,
errorMessage: error.message || '规划数据加载失败,请检查服务连接后重试'
})
this.applyCalendar({
businessStartTime: this.data.businessStartTime,
businessEndTime: this.data.businessEndTime,
artists: this.data.artists,
appointments: [],
daySummaries: []
})
}
} finally {
this.setData({ loading: false })
}
},
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'
? `${range.start.replace(/-/g, '/')} - ${range.end.replace(/-/g, '/')}`
: dateUtil.formatCnDate(current)
this.setData({
dateTitle: title,
rangeText: this.data.viewMode === 'month' ? '月视图' : this.data.viewMode === 'week' ? '周视图' : '日视图',
weekRange: `${range.start.replace(/-/g, '/')} - ${range.end.replace(/-/g, '/')}`,
monthDays: this.buildMonthDays(),
weekDays: this.buildWeekDays(),
...this.buildDayView()
})
},
buildMonthDays() {
const summaryMap = this.summaryMap()
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,
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 || [])
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 hours = []
for (let cursor = startMinute; cursor <= endMinute; cursor += 60) {
hours.push({
value: cursor,
label: dateUtil.timeFromMinutes(cursor),
top: cursor - startMinute
})
}
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 => item.date === this.data.currentDateText)
const lanes = filteredArtists.map(artist => {
const blocks = dayAppointments
.filter(item => String(item.artistId) === String(artist.id))
.map(item => {
const itemStart = item.startMinute || dateUtil.minutesOfDay((item.startTime || '').slice(11, 16))
return {
...item,
top: Math.max(0, itemStart - startMinute),
height: Math.max(64, item.durationMinutes || 60),
timeText: `${(item.startTime || '').slice(11, 16)}-${(item.endTime || '').slice(11, 16)}`
}
})
return { ...artist, blocks }
})
const pendingCount = dayAppointments.filter(item => item.status === 0).length
return {
dayLanes: lanes,
hours,
timelineHeight,
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() {
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}`
})
}
})