// appointment.js const { formatDate, appointmentDB } = require('../../utils/api') const app = getApp() // 订阅消息模板ID const SUBSCRIBE_TEMPLATE_ID = 'Csf_dJU7DhvVFt_03sphPPBCGlnmcWQSPhgqfxHZ5RQ' Page({ data: { form: { name: '', phone: '', company: '', reason: '', date: '', time: '', hostName: '', area: '' }, areas: ['A区-生产车间', 'B区-办公楼', 'C区-仓储区', 'D区-研发中心', 'E区-综合区'], areaIndex: -1, today: '', submitting: false }, onLoad() { if (!app.globalData.isLoggedIn) { wx.showToast({ title: '请先登录', icon: 'none' }) setTimeout(() => { wx.navigateBack() }, 1500) return } const today = formatDate(new Date()) this.setData({ today }) }, onNameInput(e) { this.setData({ 'form.name': e.detail.value }) }, onPhoneInput(e) { this.setData({ 'form.phone': e.detail.value }) }, onCompanyInput(e) { this.setData({ 'form.company': e.detail.value }) }, onReasonInput(e) { this.setData({ 'form.reason': e.detail.value }) }, onHostNameInput(e) { this.setData({ 'form.hostName': e.detail.value }) }, onAreaChange(e) { const index = Number(e.detail.value) this.setData({ areaIndex: index, 'form.area': this.data.areas[index] }) }, onDateChange(e) { this.setData({ 'form.date': e.detail.value }) }, onTimeChange(e) { this.setData({ 'form.time': e.detail.value }) }, validateForm() { const { name, phone, company, reason, date, time, hostName, area } = this.data.form if (!name.trim()) { wx.showToast({ title: '请输入访客姓名', icon: 'none' }) return false } if (!phone.trim() || phone.length !== 11) { wx.showToast({ title: '请输入正确的手机号', icon: 'none' }) return false } if (!company.trim()) { wx.showToast({ title: '请输入所属公司', icon: 'none' }) return false } if (!reason.trim()) { wx.showToast({ title: '请输入来访事由', icon: 'none' }) return false } if (!date) { wx.showToast({ title: '请选择来访日期', icon: 'none' }) return false } if (!time) { wx.showToast({ title: '请选择来访时间', icon: 'none' }) return false } if (!hostName.trim()) { wx.showToast({ title: '请输入被访人姓名', icon: 'none' }) return false } if (!area) { wx.showToast({ title: '请选择拜访区域', icon: 'none' }) return false } return true }, async onSubmit() { if (!this.validateForm()) return if (this.data.submitting) return // 先请求订阅消息授权,再提交预约 try { await wx.requestSubscribeMessage({ tmplIds: [SUBSCRIBE_TEMPLATE_ID] }) } catch (e) { // 用户拒绝授权也允许继续提交,只是收不到通知 console.warn('订阅消息授权失败或用户拒绝', e) } this.setData({ submitting: true }) try { const openid = app.globalData.userInfo.openid await appointmentDB.create({ ...this.data.form, openid }) this.setData({ submitting: false }) wx.showModal({ title: '提交成功', content: '您的预约已提交,请等待审核', showCancel: false, confirmText: '查看记录', confirmColor: '#1890ff', success: () => { wx.redirectTo({ url: '/pages/records/records' }) } }) } catch (err) { this.setData({ submitting: false }) console.error('提交预约失败', err) wx.showToast({ title: '提交失败,请重试', icon: 'none' }) } } })