const employeesApi = require('../../api/employees') const { chooseImageFilePath, uploadObjectFile } = require('../../utils/upload') const DEFAULT_EMPLOYEE_PASSWORD = 'Fingertip@123' Page({ data: { pickerMode: false, form: { nickname: '', phone: '', account: '', password: DEFAULT_EMPLOYEE_PASSWORD, wechatId: '', avatar: '', avatarUrl: '' }, avatarUploading: false, creating: false }, onLoad(options) { this.setData({ pickerMode: options && options.picker === '1' }) }, onInput(event) { const field = event.currentTarget.dataset.field const value = event.detail.value const updates = { [`form.${field}`]: value } if (field === 'phone' && !this.data.form.account) updates['form.account'] = value this.setData(updates) }, 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 avatarUrl = uploadResult.fileUrl || uploadResult.primaryUrl || filePath this.setData({ 'form.avatar': avatarUrl, 'form.avatarUrl': avatarUrl }) } catch (error) { wx.showToast({ title: error.message || '头像上传失败', icon: 'none' }) } finally { this.setData({ avatarUploading: false }) } }, removeAvatar() { this.setData({ 'form.avatar': '', 'form.avatarUrl': '' }) }, async submit() { const form = this.data.form const nickname = String(form.nickname || '').trim() const phone = String(form.phone || '').trim() const account = String(form.account || '').trim() const password = String(form.password || '').trim() const wechatId = String(form.wechatId || '').trim() if (!nickname || !phone || !account || !password || !wechatId) { wx.showToast({ title: '请补全员工信息', icon: 'none' }) return } if (!/^1[3-9]\d{9}$/.test(phone)) { wx.showToast({ title: '请输入正确手机号', icon: 'none' }) return } this.setData({ creating: true }) try { const result = await employeesApi.createUser({ nickname, phone, contactPhone: phone, account, password, wechatId, avatar: form.avatar || undefined, type: 3 }) const id = result && typeof result === 'object' ? (result.id || result.userId) : result const employee = { id, name: nickname, title: nickname, avatar: form.avatar || '' } const eventChannel = this.getOpenerEventChannel && this.getOpenerEventChannel() if (eventChannel && eventChannel.emit) eventChannel.emit('employeeCreated', employee) wx.showToast({ title: '员工已新增', icon: 'success' }) setTimeout(() => wx.navigateBack(), 450) } catch (error) { wx.showToast({ title: error.message || '新增失败', icon: 'none' }) } finally { this.setData({ creating: false }) } } })