/** * Soul创业派对 - 收货地址新建/编辑 */ const app = getApp() Page({ data: { statusBarHeight: 44, id: '', isEdit: false, name: '', phone: '', region: ['广东省', '广州市', '天河区'], province: '广东省', city: '广州市', district: '天河区', detail: '', isDefault: false, loading: false }, onLoad(options) { this.setData({ statusBarHeight: app.globalData.statusBarHeight }) if (options.id) { this.setData({ id: options.id, isEdit: true }) this.loadItem(options.id) } }, async loadItem(id) { wx.showLoading({ title: '加载中...' }) try { const res = await app.request('/api/user/addresses/' + id) wx.hideLoading() if (res.success && res.item) { const item = res.item this.setData({ name: item.name, phone: item.phone, province: item.province || '', city: item.city || '', district: item.district || '', region: [item.province || '', item.city || '', item.district || ''], detail: item.detail, isDefault: item.isDefault }) } } catch (e) { wx.hideLoading() wx.showToast({ title: '加载失败', icon: 'none' }) } }, onNameInput(e) { this.setData({ name: e.detail.value.trim() }) }, onPhoneInput(e) { this.setData({ phone: e.detail.value.replace(/\D/g, '').slice(0, 11) }) }, onRegionChange(e) { const region = e.detail.value this.setData({ region, province: region[0] || '', city: region[1] || '', district: region[2] || '' }) }, onDetailInput(e) { this.setData({ detail: e.detail.value.trim() }) }, onDefaultChange(e) { this.setData({ isDefault: e.detail.value }) }, async save() { const { id, isEdit, name, phone, province, city, district, detail, isDefault } = this.data if (!name) { wx.showToast({ title: '请输入收货人姓名', icon: 'none' }) return } if (!phone || !/^1[3-9]\d{9}$/.test(phone)) { wx.showToast({ title: '请输入正确的手机号', icon: 'none' }) return } // 省/市/区为选填,不校验 if (!detail) { wx.showToast({ title: '请输入详细地址', icon: 'none' }) return } const userId = app.globalData.userInfo?.id if (!userId) { wx.showToast({ title: '请先登录', icon: 'none' }) return } this.setData({ loading: true }) try { if (isEdit && id) { const res = await app.request('/api/user/addresses/' + id, { method: 'PUT', data: { name, phone, province, city, district, detail, isDefault } }) if (res.success) { wx.showToast({ title: '保存成功', icon: 'success' }) setTimeout(() => wx.navigateBack(), 1500) } else { wx.showToast({ title: res.message || '保存失败', icon: 'none' }) this.setData({ loading: false }) } } else { const res = await app.request('/api/user/addresses', { method: 'POST', data: { userId, name, phone, province, city, district, detail, isDefault } }) if (res.success) { wx.showToast({ title: '添加成功', icon: 'success' }) setTimeout(() => wx.navigateBack(), 1500) } else { wx.showToast({ title: res.message || '添加失败', icon: 'none' }) this.setData({ loading: false }) } } } catch (e) { this.setData({ loading: false }) wx.showToast({ title: '保存失败', icon: 'none' }) } }, goBack() { wx.navigateBack() } })