Initial commit
This commit is contained in:
331
miniprogram/pages/user/address/edit/index.html
Normal file
331
miniprogram/pages/user/address/edit/index.html
Normal file
@@ -0,0 +1,331 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>编辑地址</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
margin: 0;
|
||||
padding: 20px;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
.container {
|
||||
max-width: 400px;
|
||||
margin: 0 auto;
|
||||
background: white;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||
}
|
||||
.form-group {
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
label {
|
||||
display: block;
|
||||
margin-bottom: 5px;
|
||||
font-weight: 500;
|
||||
}
|
||||
input, select {
|
||||
width: 100%;
|
||||
padding: 10px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.btn {
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
background-color: #007AFF;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
font-size: 16px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.btn:hover {
|
||||
background-color: #0056CC;
|
||||
}
|
||||
.btn:disabled {
|
||||
background-color: #ccc;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.toast {
|
||||
position: fixed;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
background: rgba(0,0,0,0.8);
|
||||
color: white;
|
||||
padding: 10px 20px;
|
||||
border-radius: 4px;
|
||||
display: none;
|
||||
}
|
||||
.toast.show {
|
||||
display: block;
|
||||
}
|
||||
.checkbox-group {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.debug-info {
|
||||
margin-top: 20px;
|
||||
padding: 10px;
|
||||
background: #f0f0f0;
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
font-family: monospace;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h2>编辑地址</h2>
|
||||
<form id="addressForm">
|
||||
<div class="form-group">
|
||||
<label for="name">收货人姓名</label>
|
||||
<input type="text" id="name" name="name" required>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="phone">手机号码</label>
|
||||
<input type="tel" id="phone" name="phone" required>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="province">省份</label>
|
||||
<input type="text" id="province" name="province" required>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="city">城市</label>
|
||||
<input type="text" id="city" name="city" required>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="district">区县</label>
|
||||
<input type="text" id="district" name="district" required>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="detail">详细地址</label>
|
||||
<input type="text" id="detail" name="detail" required>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<div class="checkbox-group">
|
||||
<input type="checkbox" id="isDefault" name="isDefault">
|
||||
<label for="isDefault">设为默认地址</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn" id="submitBtn">保存地址</button>
|
||||
</form>
|
||||
|
||||
<div class="debug-info" id="debugInfo">
|
||||
<strong>调试信息:</strong><br>
|
||||
<div id="debugContent">等待加载地址数据...</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="toast" id="toast"></div>
|
||||
|
||||
<script>
|
||||
// API配置
|
||||
const API_CONFIG = {
|
||||
// 生产环境
|
||||
production: 'https://tral.cc/api/v1',
|
||||
// 开发环境
|
||||
development: 'http://localhost:8080/api/v1'
|
||||
};
|
||||
|
||||
// 当前环境 - 根据域名自动判断
|
||||
const CURRENT_ENV = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'
|
||||
? 'development'
|
||||
: 'production';
|
||||
|
||||
const API_BASE = API_CONFIG[CURRENT_ENV];
|
||||
|
||||
// 获取URL参数
|
||||
function getUrlParam(name) {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
return urlParams.get(name);
|
||||
}
|
||||
|
||||
// 获取存储的token
|
||||
function getToken() {
|
||||
return localStorage.getItem('token') || '';
|
||||
}
|
||||
|
||||
// 显示提示信息
|
||||
function showToast(message) {
|
||||
const toast = document.getElementById('toast');
|
||||
toast.textContent = message;
|
||||
toast.classList.add('show');
|
||||
setTimeout(() => {
|
||||
toast.classList.remove('show');
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
// 更新调试信息
|
||||
function updateDebugInfo(info) {
|
||||
const debugContent = document.getElementById('debugContent');
|
||||
debugContent.innerHTML = typeof info === 'object' ? JSON.stringify(info, null, 2) : info;
|
||||
}
|
||||
|
||||
// 模拟微信请求
|
||||
function wxRequest(options) {
|
||||
return fetch(options.url, {
|
||||
method: options.method || 'GET',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${getToken()}`,
|
||||
'Content-Type': 'application/json',
|
||||
...options.header
|
||||
},
|
||||
body: options.data ? JSON.stringify(options.data) : undefined
|
||||
}).then(response => {
|
||||
return response.json().then(data => ({
|
||||
statusCode: response.status,
|
||||
data: data
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
// 获取地址列表
|
||||
async function fetchAddressList() {
|
||||
try {
|
||||
const response = await wxRequest({
|
||||
url: `${API_BASE}/users/addresses`,
|
||||
method: 'GET'
|
||||
});
|
||||
|
||||
if (response.statusCode === 200 && response.data.code === 200) {
|
||||
return response.data.data || [];
|
||||
} else {
|
||||
throw new Error(response.data.message || '获取地址列表失败');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取地址列表失败:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 更新地址
|
||||
async function updateAddress(addressId, addressData) {
|
||||
try {
|
||||
updateDebugInfo(`发送更新请求: ${JSON.stringify(addressData, null, 2)}`);
|
||||
|
||||
const response = await wxRequest({
|
||||
url: `${API_BASE}/users/addresses/${addressId}`,
|
||||
method: 'PUT',
|
||||
data: addressData
|
||||
});
|
||||
|
||||
updateDebugInfo(`服务器响应: ${JSON.stringify(response, null, 2)}`);
|
||||
|
||||
if (response.statusCode === 200 && response.data.code === 200) {
|
||||
return response.data.data;
|
||||
} else {
|
||||
throw new Error(response.data.message || '更新地址失败');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('更新地址失败:', error);
|
||||
updateDebugInfo(`更新失败: ${error.message}`);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 加载地址数据
|
||||
async function loadAddressData(addressId) {
|
||||
try {
|
||||
updateDebugInfo('正在加载地址数据...');
|
||||
|
||||
// 自动设置测试token(如果没有token的话)
|
||||
if (!getToken()) {
|
||||
const testToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX3R5cGUiOiJ1c2VyIiwiaXNzIjoiZGlhbnNoYW5nIiwiZXhwIjoxNzYwMDMzMjg2LCJuYmYiOjE3NjAwMjYwODYsImlhdCI6MTc2MDAyNjA4Nn0.zCPYwDld_WDSwySyj62CWgk9xJnOUhUt3NbTc6kL4Zg';
|
||||
localStorage.setItem('token', testToken);
|
||||
console.log('自动设置测试token');
|
||||
}
|
||||
|
||||
const addressList = await fetchAddressList();
|
||||
const address = addressList.find(addr => addr.id == addressId);
|
||||
|
||||
if (address) {
|
||||
// 填充表单
|
||||
document.getElementById('name').value = address.name || '';
|
||||
document.getElementById('phone').value = address.phone || '';
|
||||
document.getElementById('province').value = address.province_name || '';
|
||||
document.getElementById('city').value = address.city_name || '';
|
||||
document.getElementById('district').value = address.district_name || '';
|
||||
document.getElementById('detail').value = address.detail_address || '';
|
||||
document.getElementById('isDefault').checked = address.is_default || false;
|
||||
|
||||
updateDebugInfo(`地址数据加载成功: ${JSON.stringify(address, null, 2)}`);
|
||||
} else {
|
||||
throw new Error('未找到指定的地址');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载地址数据失败:', error);
|
||||
updateDebugInfo(`加载失败: ${error.message}`);
|
||||
showToast('加载地址数据失败');
|
||||
}
|
||||
}
|
||||
|
||||
// 表单提交处理
|
||||
document.getElementById('addressForm').addEventListener('submit', async function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const addressId = getUrlParam('id');
|
||||
if (!addressId) {
|
||||
showToast('缺少地址ID参数');
|
||||
return;
|
||||
}
|
||||
|
||||
const formData = new FormData(this);
|
||||
const addressData = {
|
||||
name: formData.get('name'),
|
||||
phone: formData.get('phone'),
|
||||
province: formData.get('province'),
|
||||
city: formData.get('city'),
|
||||
district: formData.get('district'),
|
||||
detail: formData.get('detail'),
|
||||
is_default: document.getElementById('isDefault').checked ? 1 : 0
|
||||
};
|
||||
|
||||
const submitBtn = document.getElementById('submitBtn');
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.textContent = '保存中...';
|
||||
|
||||
try {
|
||||
const result = await updateAddress(addressId, addressData);
|
||||
showToast('地址更新成功');
|
||||
|
||||
updateDebugInfo(`更新成功,服务器返回数据: ${JSON.stringify(result, null, 2)}`);
|
||||
|
||||
// 延迟跳转回地址列表页面
|
||||
setTimeout(() => {
|
||||
window.location.href = '../list/index.html';
|
||||
}, 1500);
|
||||
|
||||
} catch (error) {
|
||||
showToast('地址更新失败');
|
||||
} finally {
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = '保存地址';
|
||||
}
|
||||
});
|
||||
|
||||
// 页面加载完成后初始化
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const addressId = getUrlParam('id');
|
||||
if (addressId) {
|
||||
loadAddressData(addressId);
|
||||
} else {
|
||||
updateDebugInfo('新建地址模式');
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
639
miniprogram/pages/user/address/edit/index.js
Normal file
639
miniprogram/pages/user/address/edit/index.js
Normal file
@@ -0,0 +1,639 @@
|
||||
import Toast from 'tdesign-miniprogram/toast/index';
|
||||
import { fetchDeliveryAddress, fetchDeliveryAddressList, createAddress, updateAddress } from '../../../../services/address/fetchAddress';
|
||||
import { areaData } from '../../../../config/index';
|
||||
import { resolveAddress, rejectAddress } from '../../../../services/address/list';
|
||||
|
||||
// 添加日志工具
|
||||
const logger = {
|
||||
info: (module, message, data = {}) => {
|
||||
console.log(`[${new Date().toISOString()}] [INFO] [${module}] ${message}`, data);
|
||||
},
|
||||
debug: (module, message, data = {}) => {
|
||||
console.log(`[${new Date().toISOString()}] [DEBUG] [${module}] ${message}`, data);
|
||||
},
|
||||
error: (module, message, data = {}) => {
|
||||
console.error(`[${new Date().toISOString()}] [ERROR] [${module}] ${message}`, data);
|
||||
},
|
||||
warn: (module, message, data = {}) => {
|
||||
console.warn(`[${new Date().toISOString()}] [WARN] [${module}] ${message}`, data);
|
||||
}
|
||||
};
|
||||
|
||||
const innerPhoneReg = '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$';
|
||||
const innerNameReg = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$';
|
||||
const labelsOptions = [
|
||||
{ id: 0, name: '家' },
|
||||
{ id: 1, name: '公司' },
|
||||
];
|
||||
|
||||
Page({
|
||||
options: {
|
||||
multipleSlots: true,
|
||||
},
|
||||
externalClasses: ['theme-wrapper-class'],
|
||||
data: {
|
||||
locationState: {
|
||||
labelIndex: null,
|
||||
addressId: '',
|
||||
addressTag: '',
|
||||
cityCode: '',
|
||||
cityName: '',
|
||||
countryCode: '',
|
||||
countryName: '',
|
||||
detailAddress: '',
|
||||
districtCode: '',
|
||||
districtName: '',
|
||||
isDefault: false,
|
||||
name: '',
|
||||
phone: '',
|
||||
provinceCode: '',
|
||||
provinceName: '',
|
||||
isEdit: false,
|
||||
isOrderDetail: false,
|
||||
isOrderSure: false,
|
||||
},
|
||||
areaData: areaData,
|
||||
labels: labelsOptions,
|
||||
areaPickerVisible: false,
|
||||
submitActive: false,
|
||||
visible: false,
|
||||
labelValue: '',
|
||||
columns: 3,
|
||||
},
|
||||
privateData: {
|
||||
verifyTips: '',
|
||||
},
|
||||
onLoad(options) {
|
||||
logger.info('ADDRESS_EDIT_PAGE', '地址编辑页面加载', { options });
|
||||
|
||||
const { id } = options;
|
||||
this.init(id);
|
||||
},
|
||||
|
||||
onUnload() {
|
||||
logger.info('ADDRESS_EDIT_PAGE', '地址编辑页面卸载', { hasSaved: this.hasSava });
|
||||
|
||||
if (!this.hasSava) {
|
||||
logger.debug('ADDRESS_EDIT_PAGE', '页面卸载时未保存,取消地址编辑');
|
||||
rejectAddress();
|
||||
}
|
||||
},
|
||||
|
||||
hasSava: false,
|
||||
isWeixinImport: false, // 标记是否为微信地址导入
|
||||
|
||||
init(id) {
|
||||
logger.info('ADDRESS_EDIT_PAGE', '初始化地址编辑页面', { addressId: id });
|
||||
|
||||
if (id) {
|
||||
logger.debug('ADDRESS_EDIT_PAGE', '编辑模式,获取地址详情');
|
||||
this.getAddressDetail(Number(id));
|
||||
} else {
|
||||
logger.debug('ADDRESS_EDIT_PAGE', '新建模式,检查用户是否有现有地址');
|
||||
this.checkUserAddressesAndSetDefault();
|
||||
}
|
||||
},
|
||||
|
||||
// 检查用户地址数量,如果没有地址则自动开启默认地址开关
|
||||
checkUserAddressesAndSetDefault() {
|
||||
logger.info('ADDRESS_EDIT_PAGE', '开始检查用户现有地址数量');
|
||||
|
||||
fetchDeliveryAddressList().then((addressList) => {
|
||||
const addressCount = addressList ? addressList.length : 0;
|
||||
|
||||
logger.info('ADDRESS_EDIT_PAGE', '用户地址数量检查完成', {
|
||||
addressCount,
|
||||
willSetDefault: addressCount === 0
|
||||
});
|
||||
|
||||
if (addressCount === 0) {
|
||||
// 用户没有地址,自动开启默认地址开关
|
||||
logger.info('ADDRESS_EDIT_PAGE', '用户没有现有地址,自动开启默认地址开关');
|
||||
|
||||
this.setData({
|
||||
'locationState.isDefault': true
|
||||
});
|
||||
|
||||
Toast({
|
||||
context: this,
|
||||
selector: '#t-toast',
|
||||
message: '已自动设置为默认地址',
|
||||
theme: 'success',
|
||||
duration: 2000,
|
||||
});
|
||||
} else {
|
||||
logger.debug('ADDRESS_EDIT_PAGE', '用户已有地址,保持默认地址开关为关闭状态');
|
||||
}
|
||||
}).catch((err) => {
|
||||
logger.error('ADDRESS_EDIT_PAGE', '检查用户地址数量失败', {
|
||||
error: err.message || err
|
||||
});
|
||||
|
||||
// 检查失败时,为了安全起见,不自动开启默认地址开关
|
||||
logger.warn('ADDRESS_EDIT_PAGE', '由于检查失败,不自动开启默认地址开关');
|
||||
});
|
||||
},
|
||||
|
||||
getAddressDetail(id) {
|
||||
logger.info('ADDRESS_EDIT_PAGE', '开始获取地址详情', { addressId: id });
|
||||
|
||||
// 获取地址列表,然后找到对应的地址
|
||||
fetchDeliveryAddressList().then((addressList) => {
|
||||
logger.debug('ADDRESS_EDIT_PAGE', '获取地址列表成功,查找目标地址', {
|
||||
totalCount: addressList.length,
|
||||
targetId: id
|
||||
});
|
||||
|
||||
const address = addressList.find(addr => addr.id == id);
|
||||
if (address) {
|
||||
logger.info('ADDRESS_EDIT_PAGE', '找到目标地址,设置编辑数据', {
|
||||
addressId: address.id,
|
||||
name: address.name,
|
||||
phone: address.phone,
|
||||
isDefault: address.isDefault
|
||||
});
|
||||
|
||||
const detail = {
|
||||
addressId: address.id,
|
||||
name: address.name,
|
||||
phone: address.phone,
|
||||
provinceName: address.province_name,
|
||||
provinceCode: address.province_code,
|
||||
cityName: address.city_name,
|
||||
cityCode: address.city_code,
|
||||
districtName: address.district_name,
|
||||
districtCode: address.district_code,
|
||||
detailAddress: address.detail_address,
|
||||
isDefault: Boolean(address.is_default),
|
||||
addressTag: address.address_tag || '',
|
||||
isEdit: true
|
||||
};
|
||||
|
||||
this.setData({ locationState: detail }, () => {
|
||||
const { isLegal, tips } = this.onVerifyInputLegal();
|
||||
this.setData({
|
||||
submitActive: isLegal,
|
||||
});
|
||||
this.privateData.verifyTips = tips;
|
||||
|
||||
logger.debug('ADDRESS_EDIT_PAGE', '地址数据设置完成', {
|
||||
isLegal,
|
||||
tips: tips || '无验证提示'
|
||||
});
|
||||
});
|
||||
} else {
|
||||
logger.warn('ADDRESS_EDIT_PAGE', '未找到目标地址', { addressId: id });
|
||||
|
||||
Toast({
|
||||
context: this,
|
||||
selector: '#t-toast',
|
||||
message: '地址不存在',
|
||||
icon: '',
|
||||
duration: 1000,
|
||||
});
|
||||
}
|
||||
}).catch((err) => {
|
||||
logger.error('ADDRESS_EDIT_PAGE', '获取地址详情失败', {
|
||||
addressId: id,
|
||||
error: err.message || err
|
||||
});
|
||||
|
||||
console.error('获取地址详情失败:', err);
|
||||
Toast({
|
||||
context: this,
|
||||
selector: '#t-toast',
|
||||
message: '获取地址详情失败',
|
||||
icon: '',
|
||||
duration: 1000,
|
||||
});
|
||||
});
|
||||
},
|
||||
onInputValue(e) {
|
||||
const { item } = e.currentTarget.dataset;
|
||||
|
||||
logger.debug('ADDRESS_EDIT_PAGE', '用户输入值变化', {
|
||||
field: item,
|
||||
eventType: e.type
|
||||
});
|
||||
|
||||
if (item === 'address') {
|
||||
const { selectedOptions = [] } = e.detail;
|
||||
|
||||
logger.info('ADDRESS_EDIT_PAGE', '用户选择地区', {
|
||||
selectedCount: selectedOptions.length,
|
||||
province: selectedOptions[0]?.label,
|
||||
city: selectedOptions[1]?.label,
|
||||
district: selectedOptions[2]?.label
|
||||
});
|
||||
|
||||
this.setData(
|
||||
{
|
||||
'locationState.provinceCode': selectedOptions.length > 0 ? selectedOptions[0].value : '',
|
||||
'locationState.provinceName': selectedOptions.length > 0 ? selectedOptions[0].label : '',
|
||||
'locationState.cityName': selectedOptions.length > 1 ? selectedOptions[1].label : '',
|
||||
'locationState.cityCode': selectedOptions.length > 1 ? selectedOptions[1].value : '',
|
||||
'locationState.districtCode': selectedOptions.length > 2 ? selectedOptions[2].value : '',
|
||||
'locationState.districtName': selectedOptions.length > 2 ? selectedOptions[2].label : '',
|
||||
areaPickerVisible: false,
|
||||
},
|
||||
() => {
|
||||
const { isLegal, tips } = this.onVerifyInputLegal();
|
||||
this.setData({
|
||||
submitActive: isLegal,
|
||||
});
|
||||
this.privateData.verifyTips = tips;
|
||||
|
||||
logger.debug('ADDRESS_EDIT_PAGE', '地区选择后验证结果', { isLegal, tips });
|
||||
},
|
||||
);
|
||||
} else {
|
||||
const { value = '' } = e.detail;
|
||||
|
||||
logger.debug('ADDRESS_EDIT_PAGE', '用户输入字段值', {
|
||||
field: item,
|
||||
valueLength: value.length,
|
||||
value: item === 'phone' ? value.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : value.substring(0, 20)
|
||||
});
|
||||
|
||||
this.setData(
|
||||
{
|
||||
[`locationState.${item}`]: value,
|
||||
},
|
||||
() => {
|
||||
const { isLegal, tips } = this.onVerifyInputLegal();
|
||||
this.setData({
|
||||
submitActive: isLegal,
|
||||
});
|
||||
this.privateData.verifyTips = tips;
|
||||
|
||||
logger.debug('ADDRESS_EDIT_PAGE', '字段输入后验证结果', {
|
||||
field: item,
|
||||
isLegal,
|
||||
tips
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
onPickArea() {
|
||||
this.setData({ areaPickerVisible: true });
|
||||
},
|
||||
onPickLabels(e) {
|
||||
const { item } = e.currentTarget.dataset;
|
||||
const {
|
||||
locationState: { labelIndex = undefined },
|
||||
labels = [],
|
||||
} = this.data;
|
||||
let payload = {
|
||||
labelIndex: item,
|
||||
addressTag: labels[item].name,
|
||||
};
|
||||
if (item === labelIndex) {
|
||||
payload = { labelIndex: null, addressTag: '' };
|
||||
}
|
||||
this.setData({
|
||||
'locationState.labelIndex': payload.labelIndex,
|
||||
});
|
||||
this.triggerEvent('triggerUpdateValue', payload);
|
||||
},
|
||||
addLabels() {
|
||||
this.setData({
|
||||
visible: true,
|
||||
});
|
||||
},
|
||||
confirmHandle() {
|
||||
const { labels, labelValue } = this.data;
|
||||
this.setData({
|
||||
visible: false,
|
||||
labels: [...labels, { id: labels[labels.length - 1].id + 1, name: labelValue }],
|
||||
labelValue: '',
|
||||
});
|
||||
},
|
||||
cancelHandle() {
|
||||
this.setData({
|
||||
visible: false,
|
||||
labelValue: '',
|
||||
});
|
||||
},
|
||||
onCheckDefaultAddress({ detail }) {
|
||||
const { value } = detail;
|
||||
this.setData({
|
||||
'locationState.isDefault': value,
|
||||
});
|
||||
},
|
||||
|
||||
onVerifyInputLegal() {
|
||||
const { name, phone, detailAddress, districtName } = this.data.locationState;
|
||||
const prefixPhoneReg = String(this.properties.phoneReg || innerPhoneReg);
|
||||
const prefixNameReg = String(this.properties.nameReg || innerNameReg);
|
||||
const nameRegExp = new RegExp(prefixNameReg);
|
||||
const phoneRegExp = new RegExp(prefixPhoneReg);
|
||||
|
||||
if (!name || !name.trim()) {
|
||||
return {
|
||||
isLegal: false,
|
||||
tips: '请填写收货人',
|
||||
};
|
||||
}
|
||||
if (!nameRegExp.test(name)) {
|
||||
return {
|
||||
isLegal: false,
|
||||
tips: '收货人仅支持输入中文、英文(区分大小写)、数字',
|
||||
};
|
||||
}
|
||||
if (!phone || !phone.trim()) {
|
||||
return {
|
||||
isLegal: false,
|
||||
tips: '请填写手机号',
|
||||
};
|
||||
}
|
||||
|
||||
// 如果是微信导入,跳过手机号格式验证
|
||||
if (this.isWeixinImport) {
|
||||
console.log('[地址编辑-验证] 微信导入模式,跳过手机号格式验证:', phone);
|
||||
} else if (!phoneRegExp.test(phone)) {
|
||||
return {
|
||||
isLegal: false,
|
||||
tips: '请填写正确的手机号',
|
||||
};
|
||||
}
|
||||
|
||||
if (!districtName || !districtName.trim()) {
|
||||
return {
|
||||
isLegal: false,
|
||||
tips: '请选择省市区信息',
|
||||
};
|
||||
}
|
||||
if (!detailAddress || !detailAddress.trim()) {
|
||||
return {
|
||||
isLegal: false,
|
||||
tips: '请完善详细地址',
|
||||
};
|
||||
}
|
||||
if (detailAddress && detailAddress.trim().length > 50) {
|
||||
return {
|
||||
isLegal: false,
|
||||
tips: '详细地址不能超过50个字符',
|
||||
};
|
||||
}
|
||||
return {
|
||||
isLegal: true,
|
||||
tips: '添加成功',
|
||||
};
|
||||
},
|
||||
|
||||
builtInSearch({ code, name }) {
|
||||
return new Promise((resolve, reject) => {
|
||||
wx.getSetting({
|
||||
success: (res) => {
|
||||
if (res.authSetting[code] === false) {
|
||||
wx.showModal({
|
||||
title: `获取${name}失败`,
|
||||
content: `获取${name}失败,请在【右上角】-小程序【设置】项中,将【${name}】开启。`,
|
||||
confirmText: '去设置',
|
||||
confirmColor: '#FA550F',
|
||||
cancelColor: '取消',
|
||||
success(res) {
|
||||
if (res.confirm) {
|
||||
wx.openSetting({
|
||||
success(settinRes) {
|
||||
if (settinRes.authSetting[code] === true) {
|
||||
resolve();
|
||||
} else {
|
||||
console.warn('用户未打开权限', name, code);
|
||||
reject();
|
||||
}
|
||||
},
|
||||
});
|
||||
} else {
|
||||
reject();
|
||||
}
|
||||
},
|
||||
fail() {
|
||||
reject();
|
||||
},
|
||||
});
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
},
|
||||
fail() {
|
||||
reject();
|
||||
},
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
onSearchAddress() {
|
||||
this.builtInSearch({ code: 'scope.userLocation', name: '地址位置' }).then(() => {
|
||||
wx.chooseLocation({
|
||||
success: (res) => {
|
||||
if (res.name) {
|
||||
this.triggerEvent('addressParse', {
|
||||
address: res.address,
|
||||
name: res.name,
|
||||
latitude: res.latitude,
|
||||
longitude: res.longitude,
|
||||
});
|
||||
} else {
|
||||
Toast({
|
||||
context: this,
|
||||
selector: '#t-toast',
|
||||
message: '地点为空,请重新选择',
|
||||
icon: '',
|
||||
duration: 1000,
|
||||
});
|
||||
}
|
||||
},
|
||||
fail: function (res) {
|
||||
console.warn(`wx.chooseLocation fail: ${JSON.stringify(res)}`);
|
||||
if (res.errMsg !== 'chooseLocation:fail cancel') {
|
||||
Toast({
|
||||
context: this,
|
||||
selector: '#t-toast',
|
||||
message: '地点错误,请重新选择',
|
||||
icon: '',
|
||||
duration: 1000,
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
});
|
||||
},
|
||||
formSubmit() {
|
||||
logger.info('ADDRESS_EDIT_PAGE', '用户提交地址表单', {
|
||||
hasSubmitActive: this.data.submitActive,
|
||||
addressId: this.data.locationState.addressId,
|
||||
isEdit: this.data.locationState.isEdit
|
||||
});
|
||||
|
||||
const { submitActive } = this.data;
|
||||
if (!submitActive) {
|
||||
logger.warn('ADDRESS_EDIT_PAGE', '表单验证失败,无法提交', {
|
||||
verifyTips: this.privateData.verifyTips
|
||||
});
|
||||
|
||||
Toast({
|
||||
context: this,
|
||||
selector: '#t-toast',
|
||||
message: this.privateData.verifyTips,
|
||||
icon: '',
|
||||
duration: 1000,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const { locationState } = this.data;
|
||||
|
||||
// 构造API请求数据
|
||||
const addressData = {
|
||||
name: locationState.name,
|
||||
phone: locationState.phone,
|
||||
province: locationState.provinceName,
|
||||
city: locationState.cityName,
|
||||
district: locationState.districtName,
|
||||
detail: locationState.detailAddress,
|
||||
is_default: locationState.isDefault ? 1 : 0,
|
||||
};
|
||||
|
||||
logger.info('ADDRESS_EDIT_PAGE', '准备提交地址数据', {
|
||||
isEdit: locationState.isEdit,
|
||||
addressId: locationState.addressId,
|
||||
locationState: {
|
||||
name: locationState.name,
|
||||
phone: locationState.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'),
|
||||
provinceName: locationState.provinceName,
|
||||
cityName: locationState.cityName,
|
||||
districtName: locationState.districtName,
|
||||
detailAddress: locationState.detailAddress,
|
||||
isDefault: locationState.isDefault
|
||||
},
|
||||
addressData: {
|
||||
...addressData,
|
||||
phone: addressData.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
|
||||
}
|
||||
});
|
||||
|
||||
const isEdit = locationState.addressId && locationState.isEdit;
|
||||
|
||||
logger.info('ADDRESS_EDIT_PAGE', `准备${isEdit ? '更新' : '创建'}地址`, {
|
||||
isEdit,
|
||||
addressId: locationState.addressId,
|
||||
name: addressData.name,
|
||||
phone: addressData.phone,
|
||||
province: addressData.provinceName,
|
||||
city: addressData.cityName,
|
||||
district: addressData.districtName,
|
||||
isDefault: addressData.isDefault,
|
||||
addressTag: addressData.addressTag
|
||||
});
|
||||
|
||||
const apiCall = isEdit
|
||||
? updateAddress(locationState.addressId, addressData)
|
||||
: createAddress(addressData);
|
||||
|
||||
apiCall.then((result) => {
|
||||
this.hasSava = true;
|
||||
|
||||
logger.info('ADDRESS_EDIT_PAGE', `地址${isEdit ? '更新' : '创建'}成功`, {
|
||||
isEdit,
|
||||
addressId: result.id || locationState.addressId,
|
||||
resultData: result,
|
||||
resultType: typeof result,
|
||||
resultKeys: result ? Object.keys(result) : 'null'
|
||||
});
|
||||
|
||||
Toast({
|
||||
context: this,
|
||||
selector: '#t-toast',
|
||||
message: isEdit ? '地址更新成功' : '地址创建成功',
|
||||
theme: 'success',
|
||||
duration: 1000,
|
||||
});
|
||||
|
||||
// 返回给地址列表页面的数据 - 优先使用服务器返回的数据
|
||||
const addressResult = {
|
||||
id: result.id || locationState.addressId,
|
||||
addressId: result.id || locationState.addressId,
|
||||
phone: result.phone || locationState.phone,
|
||||
name: result.name || locationState.name,
|
||||
provinceName: result.provinceName || locationState.provinceName,
|
||||
provinceCode: locationState.provinceCode, // 服务器不返回code,使用本地数据
|
||||
cityName: result.cityName || locationState.cityName,
|
||||
cityCode: locationState.cityCode, // 服务器不返回code,使用本地数据
|
||||
districtName: result.districtName || locationState.districtName,
|
||||
districtCode: locationState.districtCode, // 服务器不返回code,使用本地数据
|
||||
detailAddress: result.detailAddress || locationState.detailAddress,
|
||||
isDefault: result.isDefault !== undefined ? (result.isDefault ? 1 : 0) : (locationState.isDefault ? 1 : 0),
|
||||
addressTag: locationState.addressTag || '',
|
||||
isEdit: isEdit
|
||||
};
|
||||
|
||||
logger.debug('ADDRESS_EDIT_PAGE', '准备返回地址列表页面', {
|
||||
addressResult
|
||||
});
|
||||
|
||||
resolveAddress(addressResult);
|
||||
wx.navigateBack({ delta: 1 });
|
||||
}).catch((err) => {
|
||||
logger.error('ADDRESS_EDIT_PAGE', `地址${isEdit ? '更新' : '创建'}失败`, {
|
||||
isEdit,
|
||||
addressId: locationState.addressId,
|
||||
error: err.message || err,
|
||||
addressData
|
||||
});
|
||||
|
||||
console.error('保存地址失败:', err);
|
||||
Toast({
|
||||
context: this,
|
||||
selector: '#t-toast',
|
||||
message: isEdit ? '地址更新失败' : '地址创建失败',
|
||||
icon: '',
|
||||
duration: 1000,
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
getWeixinAddress(e) {
|
||||
console.log('[地址编辑-微信导入] 开始处理微信地址数据');
|
||||
console.log('[地址编辑-微信导入] 接收到的事件对象:', e);
|
||||
console.log('[地址编辑-微信导入] 事件详情数据:', e.detail);
|
||||
|
||||
const { locationState } = this.data;
|
||||
console.log('[地址编辑-微信导入] 当前locationState:', locationState);
|
||||
|
||||
const weixinAddress = e.detail;
|
||||
console.log('[地址编辑-微信导入] 微信地址数据:', weixinAddress);
|
||||
|
||||
const mergedState = { ...locationState, ...weixinAddress };
|
||||
console.log('[地址编辑-微信导入] 合并后的地址状态:', mergedState);
|
||||
|
||||
// 设置微信导入标记
|
||||
this.isWeixinImport = true;
|
||||
console.log('[地址编辑-微信导入] 设置微信导入标记,跳过手机号验证');
|
||||
|
||||
this.setData(
|
||||
{
|
||||
locationState: mergedState,
|
||||
},
|
||||
() => {
|
||||
console.log('[地址编辑-微信导入] setData完成,开始验证输入合法性');
|
||||
|
||||
const { isLegal, tips } = this.onVerifyInputLegal();
|
||||
console.log('[地址编辑-微信导入] 验证结果:', { isLegal, tips });
|
||||
|
||||
this.setData({
|
||||
submitActive: isLegal,
|
||||
});
|
||||
|
||||
this.privateData.verifyTips = tips;
|
||||
console.log('[地址编辑-微信导入] 提交按钮状态更新为:', isLegal);
|
||||
console.log('[地址编辑-微信导入] 验证提示信息:', tips);
|
||||
console.log('[地址编辑-微信导入] 微信地址数据处理完成');
|
||||
|
||||
// 重置微信导入标记
|
||||
this.isWeixinImport = false;
|
||||
},
|
||||
);
|
||||
},
|
||||
});
|
||||
16
miniprogram/pages/user/address/edit/index.json
Normal file
16
miniprogram/pages/user/address/edit/index.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"navigationBarTitleText": "添加新地址",
|
||||
"usingComponents": {
|
||||
"t-textarea": "tdesign-miniprogram/textarea/textarea",
|
||||
"t-icon": "tdesign-miniprogram/icon/icon",
|
||||
"t-input": "tdesign-miniprogram/input/input",
|
||||
"t-button": "tdesign-miniprogram/button/button",
|
||||
"t-cell-group": "tdesign-miniprogram/cell-group/cell-group",
|
||||
"t-cell": "tdesign-miniprogram/cell/cell",
|
||||
"t-toast": "tdesign-miniprogram/toast/toast",
|
||||
"t-dialog": "tdesign-miniprogram/dialog/dialog",
|
||||
"t-switch": "tdesign-miniprogram/switch/switch",
|
||||
"t-location": "/pages/user/components/t-location/index",
|
||||
"t-cascader": "tdesign-miniprogram/cascader/cascader"
|
||||
}
|
||||
}
|
||||
134
miniprogram/pages/user/address/edit/index.wxml
Normal file
134
miniprogram/pages/user/address/edit/index.wxml
Normal file
@@ -0,0 +1,134 @@
|
||||
<view class="address-detail">
|
||||
<view class="divider-line" />
|
||||
<t-location
|
||||
title="获取微信收获地址"
|
||||
isCustomStyle
|
||||
t-class="address-detail-wx-location"
|
||||
bind:change="getWeixinAddress"
|
||||
>
|
||||
<t-icon class="address-detail-wx-arrow" name="arrow_forward" prefix="wr" color="#bbb" size="32rpx" />
|
||||
</t-location>
|
||||
<view class="divider-line" />
|
||||
<view class="form-address">
|
||||
<form class="form-content">
|
||||
<t-cell-group>
|
||||
<t-cell class="form-cell" t-class-title="t-cell-title" title="收货人" t-class-note="t-cell-note">
|
||||
<t-input
|
||||
class="t-input"
|
||||
slot="note"
|
||||
t-class="field-text"
|
||||
borderless
|
||||
data-item="name"
|
||||
maxlength="20"
|
||||
type="text"
|
||||
value="{{locationState.name}}"
|
||||
placeholder="您的姓名"
|
||||
bind:change="onInputValue"
|
||||
/>
|
||||
</t-cell>
|
||||
<t-cell class="form-cell" t-class-title="t-cell-title" title="手机号">
|
||||
<t-input
|
||||
slot="note"
|
||||
class="t-input"
|
||||
t-class="field-text"
|
||||
borderless
|
||||
type="number"
|
||||
value="{{locationState.phone}}"
|
||||
maxlength="11"
|
||||
placeholder="联系您的手机号"
|
||||
bind:change="onInputValue"
|
||||
data-item="phone"
|
||||
/>
|
||||
</t-cell>
|
||||
<t-cell class="form-cell" t-class-title="t-cell-title" title="地区">
|
||||
<t-input
|
||||
slot="note"
|
||||
class="t-input"
|
||||
t-class="field-text"
|
||||
borderless
|
||||
placeholder="省/市/区"
|
||||
data-item="address"
|
||||
value="{{locationState.provinceName ? locationState.provinceName+'/':'' }}{{locationState.cityName ? locationState.cityName+'/':''}}{{locationState.districtName}}"
|
||||
catch:tap="onPickArea"
|
||||
disabled
|
||||
/>
|
||||
<t-icon slot="right-icon" t-class="map" prefix="wr" name="location" catch:tap="onSearchAddress" />
|
||||
</t-cell>
|
||||
<t-cell class="form-cell" t-class-title="t-cell-title" title="详细地址" bordered="{{false}}">
|
||||
<view slot="note" class="textarea__wrapper">
|
||||
<t-textarea
|
||||
slot="note"
|
||||
type="text"
|
||||
value="{{locationState.detailAddress}}"
|
||||
placeholder="门牌号等(例如:10栋1001号)"
|
||||
autosize
|
||||
bind:change="onInputValue"
|
||||
data-item="detailAddress"
|
||||
/>
|
||||
</view>
|
||||
</t-cell>
|
||||
|
||||
<view class="divider-line" />
|
||||
<t-cell
|
||||
class="form-cell"
|
||||
t-class-note="t-cell-note address__tag"
|
||||
t-class-title="t-cell-title"
|
||||
title="标签"
|
||||
bordered="{{false}}"
|
||||
>
|
||||
<view class="t-input address-flex-box" slot="note">
|
||||
<t-button
|
||||
wx:for="{{labels}}"
|
||||
wx:for-item="label"
|
||||
wx:key="index"
|
||||
size="extra-small"
|
||||
t-class="label-list {{locationState.labelIndex === index ? 'active-btn':''}}"
|
||||
bindtap="onPickLabels"
|
||||
data-item="{{index}}"
|
||||
>
|
||||
{{label.name}}
|
||||
</t-button>
|
||||
<t-button size="extra-small" t-class="label-list" bindtap="addLabels">
|
||||
<t-icon name="add" size="40rpx" color="#bbb" />
|
||||
</t-button>
|
||||
</view>
|
||||
</t-cell>
|
||||
<view class="divider-line" />
|
||||
<t-cell title="设置为默认收货地址" bordered="{{false}}">
|
||||
<t-switch
|
||||
value="{{locationState.isDefault}}"
|
||||
slot="note"
|
||||
colors="{{['#0ABF5B', '#c6c6c6']}}"
|
||||
bind:change="onCheckDefaultAddress"
|
||||
/>
|
||||
</t-cell>
|
||||
</t-cell-group>
|
||||
<view class="submit">
|
||||
<t-button shape="round" block disabled="{{!submitActive}}" bind:tap="formSubmit"> 保存 </t-button>
|
||||
</view>
|
||||
</form>
|
||||
</view>
|
||||
<t-cascader
|
||||
data-item="address"
|
||||
data-type="1"
|
||||
visible="{{areaPickerVisible}}"
|
||||
theme="tab"
|
||||
options="{{areaData}}"
|
||||
value="{{locationState.districtCode}}"
|
||||
title="选择地区"
|
||||
bind:change="onInputValue"
|
||||
></t-cascader>
|
||||
</view>
|
||||
<t-dialog
|
||||
visible="{{visible}}"
|
||||
t-class-confirm="dialog__button-confirm"
|
||||
t-class-cancel="dialog__button-cancel"
|
||||
title="填写标签名称"
|
||||
confirm-btn="确定"
|
||||
cancel-btn="取消"
|
||||
bind:confirm="confirmHandle"
|
||||
bind:cancel="cancelHandle"
|
||||
>
|
||||
<t-input slot="content" class="dialog__input" model:value="{{labelValue}}" placeholder="请输入标签名称" borderless />
|
||||
</t-dialog>
|
||||
<t-toast id="t-toast" />
|
||||
95
miniprogram/pages/user/address/edit/index.wxss
Normal file
95
miniprogram/pages/user/address/edit/index.wxss
Normal file
@@ -0,0 +1,95 @@
|
||||
page {
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
page .divider-line {
|
||||
width: 100%;
|
||||
height: 20rpx;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
.address-flex-box {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.address-detail {
|
||||
font-size: 30rpx;
|
||||
}
|
||||
.address-detail-wx-location {
|
||||
background: #fff;
|
||||
padding: 24rpx 32rpx;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.address-detail-wx-arrow {
|
||||
align-items: flex-end;
|
||||
}
|
||||
|
||||
.form-cell .t-cell__title {
|
||||
width: 144rpx;
|
||||
padding-right: 32rpx;
|
||||
flex: none !important;
|
||||
}
|
||||
|
||||
.textarea__wrapper {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.textarea__wrapper .t-textarea {
|
||||
padding: 0 !important;
|
||||
}
|
||||
|
||||
.form-address .map {
|
||||
font-size: 48rpx !important;
|
||||
margin-left: 20rpx;
|
||||
color: #9d9d9f;
|
||||
}
|
||||
|
||||
.address__tag {
|
||||
justify-content: flex-start !important;
|
||||
}
|
||||
|
||||
.form-address .label-list {
|
||||
background: #f5f5f5;
|
||||
color: #333;
|
||||
min-width: 100rpx;
|
||||
margin-right: 32rpx;
|
||||
font-size: 26rpx;
|
||||
border: 2rpx solid transparent;
|
||||
width: auto;
|
||||
}
|
||||
.form-address .label-list::after {
|
||||
content: none;
|
||||
}
|
||||
.form-address .active-btn {
|
||||
color: #fa4126;
|
||||
border: 2rpx solid #fa4126;
|
||||
background: rgba(255, 95, 21, 0.04);
|
||||
}
|
||||
.form-address .active-btn::after {
|
||||
border: 4rpx solid #ff5f15;
|
||||
}
|
||||
|
||||
.submit {
|
||||
box-sizing: border-box;
|
||||
padding: 64rpx 30rpx 88rpx 30rpx;
|
||||
}
|
||||
.submit .btn-submit-address {
|
||||
background: #fa4126 !important;
|
||||
color: #fff !important;
|
||||
}
|
||||
|
||||
.dialog__button-confirm {
|
||||
color: #fa4126 !important;
|
||||
}
|
||||
|
||||
.form-address .form-content {
|
||||
--td-input-vertical-padding: 0;
|
||||
}
|
||||
|
||||
.dialog__input {
|
||||
margin-top: 32rpx;
|
||||
border-radius: 8rpx;
|
||||
box-sizing: border-box;
|
||||
--td-input-vertical-padding: 12px;
|
||||
--td-input-bg-color: #f3f3f3;
|
||||
}
|
||||
Reference in New Issue
Block a user