532 lines
19 KiB
JavaScript
532 lines
19 KiB
JavaScript
const employeesApi = require('../../api/employees')
|
|
const { chooseImageFilePath, uploadObjectFile } = require('../../utils/upload')
|
|
const { showErrorToast, toUserMessage } = require('../../utils/toast')
|
|
const { showActionModal } = require('../../utils/action-modal')
|
|
const { markPlanningRefresh } = require('../../utils/planning-refresh')
|
|
|
|
const EMPLOYEE_COLORS = ['#7BA7C7', '#8FB89A', '#A894C7', '#D7A86E', '#D98DA5', '#79A6A3', '#B9A16B', '#9BA9C8']
|
|
const COLOR_WHEEL_RADIUS = 110
|
|
|
|
function clamp(value, min, max) {
|
|
return Math.min(max, Math.max(min, value))
|
|
}
|
|
|
|
function normalizeHex(value) {
|
|
const raw = String(value || '').trim().replace('#', '')
|
|
if (/^[0-9a-fA-F]{3}$/.test(raw)) {
|
|
return ('#' + raw.split('').map(char => char + char).join('')).toUpperCase()
|
|
}
|
|
if (/^[0-9a-fA-F]{6}$/.test(raw)) return ('#' + raw).toUpperCase()
|
|
return ''
|
|
}
|
|
|
|
function rgbToHex(red, green, blue) {
|
|
return ('#' + [red, green, blue]
|
|
.map(value => Math.round(clamp(value, 0, 255)).toString(16).padStart(2, '0'))
|
|
.join('')).toUpperCase()
|
|
}
|
|
|
|
function hsvToHex(hue, saturation) {
|
|
const normalizedHue = ((Number(hue) % 360) + 360) % 360
|
|
const s = clamp(Number(saturation) || 0, 0, 1)
|
|
const chroma = s
|
|
const x = chroma * (1 - Math.abs(((normalizedHue / 60) % 2) - 1))
|
|
const offset = 1 - chroma
|
|
let red = 0
|
|
let green = 0
|
|
let blue = 0
|
|
if (normalizedHue < 60) { red = chroma; green = x }
|
|
else if (normalizedHue < 120) { red = x; green = chroma }
|
|
else if (normalizedHue < 180) { green = chroma; blue = x }
|
|
else if (normalizedHue < 240) { green = x; blue = chroma }
|
|
else if (normalizedHue < 300) { red = x; blue = chroma }
|
|
else { red = chroma; blue = x }
|
|
return rgbToHex((red + offset) * 255, (green + offset) * 255, (blue + offset) * 255)
|
|
}
|
|
|
|
function hexToHsv(value) {
|
|
const hex = normalizeHex(value) || '#8FB89A'
|
|
const red = parseInt(hex.slice(1, 3), 16) / 255
|
|
const green = parseInt(hex.slice(3, 5), 16) / 255
|
|
const blue = parseInt(hex.slice(5, 7), 16) / 255
|
|
const max = Math.max(red, green, blue)
|
|
const min = Math.min(red, green, blue)
|
|
const delta = max - min
|
|
let hue = 0
|
|
if (delta === 0) hue = 0
|
|
else if (max === red) hue = 60 * (((green - blue) / delta) % 6)
|
|
else if (max === green) hue = 60 * ((blue - red) / delta + 2)
|
|
else hue = 60 * ((red - green) / delta + 4)
|
|
return {
|
|
hue: ((hue % 360) + 360) % 360,
|
|
saturation: max === 0 ? 0 : delta / max
|
|
}
|
|
}
|
|
|
|
Page({
|
|
data: {
|
|
pickerMode: false,
|
|
appointmentContext: { date: '', time: '', durationMinutes: '' },
|
|
applicationId: '',
|
|
employeeColors: EMPLOYEE_COLORS,
|
|
colorSheetVisible: false,
|
|
colorDraft: '#8FB89A',
|
|
colorHexInput: '#8FB89A',
|
|
wheelDotX: COLOR_WHEEL_RADIUS,
|
|
wheelDotY: 0,
|
|
onboardingVisible: false,
|
|
createdEmployee: null,
|
|
userPickerVisible: false,
|
|
userLoading: false,
|
|
userKeyword: '',
|
|
userCandidates: [],
|
|
userItems: [],
|
|
selectedWechatUserId: '',
|
|
selectedWechatUser: null,
|
|
associationSheetVisible: false,
|
|
associationLoading: false,
|
|
associationApplications: [],
|
|
associationItems: [],
|
|
associationKeyword: '',
|
|
associationSelectedId: '',
|
|
form: {
|
|
nickname: '',
|
|
phone: '',
|
|
wechatId: '',
|
|
color: '#8FB89A',
|
|
avatar: '',
|
|
avatarUrl: ''
|
|
},
|
|
avatarUploading: false,
|
|
creating: false
|
|
},
|
|
|
|
onLoad(options) {
|
|
this.setData({
|
|
pickerMode: options && options.picker === '1',
|
|
appointmentContext: {
|
|
date: options.date || '',
|
|
time: options.time || '',
|
|
durationMinutes: options.durationMinutes || ''
|
|
},
|
|
applicationId: options.applicationId || '',
|
|
applicationNo: options.applicationNo || ''
|
|
})
|
|
},
|
|
|
|
onInput(event) {
|
|
const field = event.currentTarget.dataset.field
|
|
const value = event.detail.value
|
|
this.setData({ [`form.${field}`]: value })
|
|
},
|
|
|
|
openColorSheet() {
|
|
const color = normalizeHex(this.data.form.color) || '#8FB89A'
|
|
this.setData({ colorSheetVisible: true, colorDraft: color, colorHexInput: color })
|
|
this.applyDraftColor(color)
|
|
if (typeof wx.nextTick === 'function') {
|
|
wx.nextTick(() => {
|
|
wx.createSelectorQuery().in(this).select('.color-wheel').boundingClientRect(rect => {
|
|
this._wheelRect = rect
|
|
}).exec()
|
|
})
|
|
}
|
|
},
|
|
|
|
closeColorSheet() {
|
|
this.setData({ colorSheetVisible: false })
|
|
},
|
|
|
|
stopColorSheetTap() {},
|
|
|
|
pickDraftColor(event) {
|
|
const color = normalizeHex(event.currentTarget.dataset.color)
|
|
if (color) this.applyDraftColor(color)
|
|
},
|
|
|
|
onColorHexInput(event) {
|
|
this.setData({ colorHexInput: event.detail.value })
|
|
},
|
|
|
|
applyColorHex() {
|
|
const color = normalizeHex(this.data.colorHexInput)
|
|
if (!color) {
|
|
wx.showToast({ title: '请输入有效的十六进制色值', icon: 'none' })
|
|
return
|
|
}
|
|
this.applyDraftColor(color)
|
|
},
|
|
|
|
applyDraftColor(color) {
|
|
const { hue, saturation } = hexToHsv(color)
|
|
const angle = (hue - 90) * Math.PI / 180
|
|
const distance = saturation * COLOR_WHEEL_RADIUS
|
|
this.setData({
|
|
colorDraft: color,
|
|
colorHexInput: color,
|
|
wheelDotX: Math.round(COLOR_WHEEL_RADIUS + Math.cos(angle) * distance),
|
|
wheelDotY: Math.round(COLOR_WHEEL_RADIUS + Math.sin(angle) * distance)
|
|
})
|
|
},
|
|
|
|
applyWheelPoint(clientX, clientY) {
|
|
const rect = this._wheelRect
|
|
if (!rect || !rect.width) return
|
|
const centerX = rect.left + rect.width / 2
|
|
const centerY = rect.top + rect.height / 2
|
|
const radius = rect.width / 2
|
|
const offsetX = clientX - centerX
|
|
const offsetY = clientY - centerY
|
|
const distance = Math.min(radius, Math.sqrt(offsetX * offsetX + offsetY * offsetY))
|
|
const hue = ((Math.atan2(offsetY, offsetX) * 180 / Math.PI + 90) % 360 + 360) % 360
|
|
this.applyDraftColor(hsvToHex(hue, radius ? distance / radius : 0))
|
|
},
|
|
|
|
onWheelTap(event) {
|
|
const touch = event.touches && event.touches[0]
|
|
if (touch) this.applyWheelPoint(touch.clientX, touch.clientY)
|
|
},
|
|
|
|
onWheelTouch(event) {
|
|
const touch = event.touches && event.touches[0]
|
|
if (touch) this.applyWheelPoint(touch.clientX, touch.clientY)
|
|
},
|
|
|
|
saveColorSheet() {
|
|
this.setData({ 'form.color': this.data.colorDraft, colorSheetVisible: false })
|
|
},
|
|
|
|
async openUserPicker() {
|
|
if (this.data.creating || this.data.avatarUploading) return
|
|
this.setData({ userPickerVisible: true, userLoading: true, userKeyword: '' })
|
|
try {
|
|
const list = await employeesApi.unlinkedCandidates()
|
|
this.applyUserCandidates(Array.isArray(list) ? list : (list && list.list) || [])
|
|
} catch (error) {
|
|
showErrorToast(error, '微信用户加载失败')
|
|
} finally {
|
|
this.setData({ userLoading: false })
|
|
}
|
|
},
|
|
|
|
applyUserCandidates(candidates) {
|
|
this.setData({
|
|
userCandidates: candidates,
|
|
userItems: candidates.map(item => ({
|
|
id: String(item.id),
|
|
title: item.nickname || '微信用户',
|
|
subtitle: [item.maskedPhone || item.phone, item.createTime && String(item.createTime).replace('T', ' ').slice(0, 10)].filter(Boolean).join(' · ') || '已登录小程序',
|
|
meta: item.wechatId || '',
|
|
avatar: item.avatar || ''
|
|
}))
|
|
})
|
|
},
|
|
|
|
onUserSearch(event) {
|
|
const userKeyword = String(event.detail.value || '').trim().toLowerCase()
|
|
const candidates = this.data.userCandidates
|
|
const userItems = candidates
|
|
.filter(item => !userKeyword || [item.nickname, item.maskedPhone, item.phone, item.wechatId]
|
|
.some(value => String(value || '').toLowerCase().includes(userKeyword)))
|
|
.map(item => ({
|
|
id: String(item.id),
|
|
title: item.nickname || '微信用户',
|
|
subtitle: [item.maskedPhone || item.phone, item.createTime && String(item.createTime).replace('T', ' ').slice(0, 10)].filter(Boolean).join(' · ') || '已登录小程序',
|
|
meta: item.wechatId || '',
|
|
avatar: item.avatar || ''
|
|
}))
|
|
this.setData({ userKeyword, userItems })
|
|
},
|
|
|
|
selectWechatUser(event) {
|
|
const item = event.detail && event.detail.item
|
|
if (!item) return
|
|
const candidate = this.data.userCandidates.find(user => String(user.id) === String(item.id))
|
|
if (!candidate) return
|
|
this.setData({
|
|
userPickerVisible: false,
|
|
selectedWechatUserId: String(candidate.id),
|
|
selectedWechatUser: item,
|
|
'form.nickname': candidate.nickname || '',
|
|
'form.avatar': candidate.avatar || '',
|
|
'form.avatarUrl': candidate.avatar || ''
|
|
})
|
|
},
|
|
|
|
closeUserPicker() {
|
|
if (this.data.userLoading) return
|
|
this.setData({ userPickerVisible: false })
|
|
},
|
|
|
|
async chooseAvatar() {
|
|
if (this.data.avatarUploading || this.data.creating) return
|
|
try {
|
|
const filePath = await chooseImageFilePath()
|
|
if (!filePath) return
|
|
this.setData({ avatarUploading: true })
|
|
const uploadResult = await uploadObjectFile(filePath)
|
|
// 私有对象存储地址可能无法被小程序直接访问,上传完成后先用本地临时文件即时预览。
|
|
const storedAvatar = uploadResult.fileUrl || uploadResult.primaryUrl || ''
|
|
this.setData({
|
|
'form.avatar': storedAvatar,
|
|
'form.avatarUrl': filePath
|
|
})
|
|
} catch (error) {
|
|
showErrorToast(error, '头像上传失败')
|
|
} finally {
|
|
this.setData({ avatarUploading: false })
|
|
}
|
|
},
|
|
|
|
removeAvatar() {
|
|
this.setData({ 'form.avatar': '', 'form.avatarUrl': '' })
|
|
},
|
|
|
|
onAvatarError() {
|
|
this.setData({ 'form.avatarUrl': '' })
|
|
},
|
|
|
|
stopTouchMove() {
|
|
},
|
|
|
|
async submit() {
|
|
if (this.data.creating || this.data.avatarUploading) return
|
|
if (this.data.createdEmployee) {
|
|
if (this.data.applicationId && !this.data.applicationApproved) return this.associateCreatedEmployee()
|
|
this.setData({ onboardingVisible: true })
|
|
return
|
|
}
|
|
const form = this.data.form
|
|
const nickname = String(form.nickname || '').trim()
|
|
const phone = String(form.phone || '').trim()
|
|
const wechatId = String(form.wechatId || '').trim()
|
|
if (this.data.selectedWechatUserId) {
|
|
if (!nickname) {
|
|
wx.showToast({ title: '请填写美甲师姓名', icon: 'none' })
|
|
return
|
|
}
|
|
this.setData({ creating: true })
|
|
try {
|
|
const saved = await employeesApi.save({
|
|
userId: this.data.selectedWechatUserId,
|
|
nickname,
|
|
color: form.color,
|
|
avatar: form.avatar || undefined
|
|
})
|
|
const id = saved && typeof saved === 'object' ? (saved.userId || saved.id) : this.data.selectedWechatUserId
|
|
markPlanningRefresh()
|
|
this.setData({
|
|
createdEmployee: { id, name: nickname, title: nickname, avatar: form.avatar || '' },
|
|
applicationApproved: false
|
|
})
|
|
await this.offerPendingAssociation()
|
|
} catch (error) {
|
|
showErrorToast(error, '新增失败')
|
|
} finally {
|
|
this.setData({ creating: false })
|
|
}
|
|
return
|
|
}
|
|
if (!nickname) {
|
|
wx.showToast({ title: '请填写美甲师姓名', icon: 'none' })
|
|
return
|
|
}
|
|
if (phone && !/^1[3-9]\d{9}$/.test(phone)) {
|
|
wx.showToast({ title: '请输入正确手机号', icon: 'none' })
|
|
return
|
|
}
|
|
this.setData({ creating: true })
|
|
try {
|
|
const payload = {
|
|
nickname,
|
|
wechatId,
|
|
color: form.color,
|
|
avatar: form.avatar || undefined,
|
|
type: 3
|
|
}
|
|
if (phone) {
|
|
payload.phone = phone
|
|
payload.contactPhone = phone
|
|
}
|
|
const result = await employeesApi.createUser(payload)
|
|
const id = result && typeof result === 'object' ? (result.id || result.userId) : result
|
|
markPlanningRefresh()
|
|
const employee = { id, name: nickname, title: nickname, avatar: form.avatar || '' }
|
|
this.setData({ createdEmployee: employee, applicationApproved: false })
|
|
if (this.data.applicationId) {
|
|
await this.associateCreatedEmployee()
|
|
return
|
|
}
|
|
await this.offerPendingAssociation()
|
|
} catch (error) {
|
|
showErrorToast(error, '新增失败')
|
|
} finally {
|
|
this.setData({ creating: false })
|
|
}
|
|
},
|
|
|
|
async associateCreatedEmployee() {
|
|
const employee = this.data.createdEmployee
|
|
if (!employee || !employee.id || !this.data.applicationId || this.data.associatingApplication) return
|
|
this.setData({ associatingApplication: true })
|
|
try {
|
|
await employeesApi.approveApplication(this.data.applicationId, {
|
|
targetArtistUserId: employee.id,
|
|
useApplicantNickname: false,
|
|
useApplicantAvatar: false
|
|
})
|
|
this.setData({ applicationApproved: true, associatingApplication: false, onboardingVisible: true })
|
|
wx.showToast({ title: '已关联并通过审核', icon: 'success' })
|
|
} catch (error) {
|
|
this.setData({ associatingApplication: false })
|
|
const result = await showActionModal(this, {
|
|
title: '关联审核未完成',
|
|
content: toUserMessage(error, '美甲师档案已创建,可重试关联申请。'),
|
|
icon: 'warning',
|
|
confirmText: '重试',
|
|
cancelText: '稍后处理'
|
|
})
|
|
if (result.confirm) this.associateCreatedEmployee()
|
|
else this.setData({ onboardingVisible: true })
|
|
}
|
|
},
|
|
|
|
async offerPendingAssociation() {
|
|
try {
|
|
const data = await employeesApi.unassociatedApplications()
|
|
const applications = Array.isArray(data) ? data : []
|
|
if (!applications.length) {
|
|
this.setData({ onboardingVisible: true })
|
|
return
|
|
}
|
|
const associationItems = applications.map(item => ({
|
|
id: item.id,
|
|
title: item.applicantNickname || '待审核美甲师申请',
|
|
subtitle: [item.applicantMaskedPhone, item.createTime && String(item.createTime).replace('T', ' ').slice(0, 16)].filter(Boolean).join(' · ') || '申请资料尚未审核',
|
|
meta: item.applicationNo || ''
|
|
}))
|
|
this.setData({
|
|
associationApplications: applications,
|
|
associationItems,
|
|
associationKeyword: '',
|
|
associationSelectedId: '',
|
|
associationSheetVisible: true
|
|
})
|
|
} catch (error) {
|
|
wx.showToast({ title: '申请列表暂时不可用,已继续新增员工', icon: 'none' })
|
|
this.setData({ onboardingVisible: true })
|
|
}
|
|
},
|
|
|
|
onAssociationSearch(event) {
|
|
const associationKeyword = String(event.detail.value || '').trim().toLowerCase()
|
|
const applications = this.data.associationApplications
|
|
const associationItems = applications
|
|
.filter(item => !associationKeyword || [item.applicantNickname, item.applicantMaskedPhone, item.applicationNo]
|
|
.some(value => String(value || '').toLowerCase().includes(associationKeyword)))
|
|
.map(item => ({
|
|
id: item.id,
|
|
title: item.applicantNickname || '待审核美甲师申请',
|
|
subtitle: [item.applicantMaskedPhone, item.createTime && String(item.createTime).replace('T', ' ').slice(0, 16)].filter(Boolean).join(' · ') || '申请资料尚未审核',
|
|
meta: item.applicationNo || ''
|
|
}))
|
|
this.setData({ associationKeyword, associationItems })
|
|
},
|
|
|
|
async selectAssociation(event) {
|
|
const application = event.detail && event.detail.item
|
|
const employee = this.data.createdEmployee
|
|
if (!application || !employee || !employee.id || this.data.associationLoading) return
|
|
this.setData({ associationLoading: true, associationSelectedId: application.id })
|
|
try {
|
|
await employeesApi.preAssociateApplication(application.id, employee.id)
|
|
this.setData({ associationSheetVisible: false, onboardingVisible: true })
|
|
wx.showToast({ title: '已预关联申请', icon: 'success' })
|
|
} catch (error) {
|
|
showErrorToast(error, '关联失败,请重新选择')
|
|
this.setData({ associationSelectedId: '' })
|
|
} finally {
|
|
this.setData({ associationLoading: false })
|
|
}
|
|
},
|
|
|
|
skipAssociation() {
|
|
if (this.data.associationLoading) return
|
|
this.setData({ associationSheetVisible: false, onboardingVisible: true })
|
|
},
|
|
|
|
setupFirstSchedule() {
|
|
if (this.data.applicationId && !this.data.applicationApproved) return
|
|
const employee = this.data.createdEmployee
|
|
if (!employee || !employee.id) return
|
|
const context = this.data.appointmentContext
|
|
const query = [
|
|
`id=${encodeURIComponent(employee.id)}`,
|
|
'onboarding=1',
|
|
`source=${this.data.pickerMode ? 'appointment' : 'employees'}`,
|
|
`date=${encodeURIComponent(context.date || '')}`,
|
|
`time=${encodeURIComponent(context.time || '')}`,
|
|
`durationMinutes=${encodeURIComponent(context.durationMinutes || '')}`
|
|
]
|
|
wx.navigateTo({
|
|
url: `/pages/schedule-setting/index?${query.join('&')}`,
|
|
success: result => {
|
|
result.eventChannel.on('scheduleSaved', () => {
|
|
setTimeout(() => this.finishCreated(this.data.pickerMode, true), 250)
|
|
})
|
|
}
|
|
})
|
|
},
|
|
|
|
skipFirstSchedule() {
|
|
if (this.data.savingDefaultSchedule || !this.data.createdEmployee || (this.data.applicationId && !this.data.applicationApproved)) return
|
|
this.setData({ savingDefaultSchedule: true })
|
|
employeesApi.saveScheduleRule({
|
|
artistId: this.data.createdEmployee.id,
|
|
presetType: 'CUSTOM',
|
|
workDays: [1, 2, 3, 4, 5, 6, 7],
|
|
startTime: '00:00',
|
|
endTime: '23:59',
|
|
status: 1,
|
|
remark: '新建美甲师默认全年全天排班,预约仍受门店营业时间限制,可在排班设置中调整'
|
|
}).then(() => {
|
|
this.finishCreated(this.data.pickerMode, true)
|
|
}).catch(async error => {
|
|
const result = await showActionModal(this, {
|
|
title: '默认排班设置失败',
|
|
content: toUserMessage(error, '未设置排班前,该美甲师暂不可预约。请重试或返回排班设置。'),
|
|
confirmText: '重试',
|
|
cancelText: '稍后设置'
|
|
})
|
|
if (result.confirm) this.skipFirstSchedule()
|
|
else this.setData({ savingDefaultSchedule: false })
|
|
}).finally(() => {
|
|
if (this.data.onboardingVisible) this.setData({ savingDefaultSchedule: false })
|
|
})
|
|
},
|
|
|
|
finishCreated(autoSelect, scheduleSaved) {
|
|
if (this.data.applicationId && !this.data.applicationApproved) {
|
|
this.setData({ onboardingVisible: true })
|
|
return
|
|
}
|
|
const employee = this.data.createdEmployee
|
|
const eventChannel = this.getOpenerEventChannel && this.getOpenerEventChannel()
|
|
if (eventChannel && eventChannel.emit) {
|
|
eventChannel.emit('employeeCreated', { ...employee, autoSelect, scheduleSaved })
|
|
}
|
|
this.setData({ onboardingVisible: false })
|
|
wx.showToast({ title: scheduleSaved ? '排班已保存' : '美甲师已新增', icon: 'success' })
|
|
setTimeout(() => wx.navigateBack(), 300)
|
|
},
|
|
|
|
leaveAssociationForLater() {
|
|
const employee = this.data.createdEmployee
|
|
const eventChannel = this.getOpenerEventChannel && this.getOpenerEventChannel()
|
|
if (eventChannel && eventChannel.emit && employee) {
|
|
eventChannel.emit('employeeCreated', { ...employee, autoSelect: this.data.pickerMode, scheduleSaved: false })
|
|
}
|
|
wx.navigateBack()
|
|
}
|
|
})
|