This commit is contained in:
sjk
2025-11-17 14:11:46 +08:00
commit ad4a600af9
1659 changed files with 171560 additions and 0 deletions

BIN
miniprogram/pages/user/.DS_Store vendored Normal file

Binary file not shown.

View 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>

View 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;
},
);
},
});

View 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"
}
}

View 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" />

View 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;
}

View File

@@ -0,0 +1,484 @@
<!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>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background-color: #f5f5f5;
color: #333;
}
.header {
background: #fff;
padding: 16px;
border-bottom: 1px solid #eee;
position: sticky;
top: 0;
z-index: 100;
}
.header h1 {
font-size: 18px;
font-weight: 500;
text-align: center;
}
.container {
padding: 16px;
}
.address-list {
background: #fff;
border-radius: 8px;
overflow: hidden;
}
.address-item {
padding: 16px;
border-bottom: 1px solid #f0f0f0;
position: relative;
}
.address-item:last-child {
border-bottom: none;
}
.address-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8px;
}
.user-info {
font-size: 16px;
font-weight: 500;
}
.default-tag {
background: #ff6b35;
color: white;
padding: 2px 8px;
border-radius: 4px;
font-size: 12px;
}
.address-detail {
color: #666;
line-height: 1.5;
margin-bottom: 12px;
}
.address-actions {
display: flex;
gap: 16px;
}
.action-btn {
background: none;
border: 1px solid #ddd;
padding: 6px 12px;
border-radius: 4px;
font-size: 14px;
cursor: pointer;
transition: all 0.2s;
}
.action-btn:hover {
background: #f5f5f5;
}
.action-btn.primary {
background: #ff6b35;
color: white;
border-color: #ff6b35;
}
.action-btn.primary:hover {
background: #e55a2b;
}
.action-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.add-address {
position: fixed;
bottom: 20px;
right: 20px;
width: 56px;
height: 56px;
background: #ff6b35;
border: none;
border-radius: 50%;
color: white;
font-size: 24px;
cursor: pointer;
box-shadow: 0 4px 12px rgba(255, 107, 53, 0.3);
transition: all 0.2s;
}
.add-address:hover {
transform: scale(1.1);
box-shadow: 0 6px 16px rgba(255, 107, 53, 0.4);
}
.loading, .error, .empty {
text-align: center;
padding: 40px 20px;
color: #666;
}
.loading {
font-size: 16px;
}
.error {
color: #ff4757;
}
.empty {
color: #999;
}
.hidden {
display: none;
}
.toast {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0, 0, 0, 0.8);
color: white;
padding: 12px 24px;
border-radius: 4px;
z-index: 1000;
opacity: 0;
transition: opacity 0.3s;
}
.toast.show {
opacity: 1;
}
.test-controls {
position: fixed;
top: 10px;
right: 10px;
z-index: 1001;
display: flex;
gap: 8px;
}
.test-btn {
background: #007aff;
color: white;
border: none;
padding: 6px 12px;
border-radius: 4px;
font-size: 12px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="header">
<h1>收货地址</h1>
</div>
<div class="container">
<div id="loading" class="loading">
加载中...
</div>
<div id="error" class="error hidden">
加载失败,请重试
<br><br>
<button class="action-btn" onclick="loadAddresses()">重新加载</button>
</div>
<div id="empty" class="empty hidden">
暂无收货地址
<br><br>
<button class="action-btn primary" onclick="addAddress()">添加地址</button>
</div>
<div id="addressList" class="address-list hidden">
<!-- 地址列表将在这里动态生成 -->
</div>
</div>
<button class="add-address" onclick="addAddress()">+</button>
<div id="toast" class="toast"></div>
<!-- 测试控制按钮 -->
<div class="test-controls">
<button class="test-btn" onclick="generateTestToken()">生成Token</button>
<button class="test-btn" onclick="toggleMock()">切换模式</button>
</div>
<script>
// 配置
const config = {
apiBase: 'http://127.0.0.1:8080/api/v1',
useMock: false
};
// 全局变量
let addresses = [];
let isLoading = false;
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
// 自动设置测试token如果没有token的话
if (!getToken()) {
const testToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX3R5cGUiOiJ1c2VyIiwiaXNzIjoiZGlhbnNoYW5nIiwiZXhwIjoxNzYwMDMzMjg2LCJuYmYiOjE3NjAwMjYwODYsImlhdCI6MTc2MDAyNjA4Nn0.zCPYwDld_WDSwySyj62CWgk9xJnOUhUt3NbTc6kL4Zg';
localStorage.setItem('token', testToken);
console.log('自动设置测试token');
}
loadAddresses();
});
// 显示提示信息
function showToast(message) {
const toast = document.getElementById('toast');
toast.textContent = message;
toast.classList.add('show');
setTimeout(() => {
toast.classList.remove('show');
}, 2000);
}
// 获取存储的token
function getToken() {
return localStorage.getItem('token') || '';
}
// 模拟微信请求
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 loadAddresses() {
if (isLoading) return;
isLoading = true;
showLoading();
try {
if (config.useMock) {
// 使用模拟数据
await new Promise(resolve => setTimeout(resolve, 1000));
addresses = [
{
id: 1,
name: '张三',
phone: '13800138000',
provinceName: '北京市',
cityName: '北京市',
districtName: '朝阳区',
detailAddress: '三里屯街道工体北路8号',
isDefault: true
},
{
id: 2,
name: '李四',
phone: '13900139000',
provinceName: '上海市',
cityName: '上海市',
districtName: '黄浦区',
detailAddress: '南京东路100号',
isDefault: false
}
];
displayAddresses();
} else {
// 调用真实API
const res = await wxRequest({
url: `${config.apiBase}/users/addresses`,
method: 'GET'
});
if (res.statusCode === 200 && res.data.code === 200) {
addresses = res.data.data || [];
displayAddresses();
} else {
throw new Error(res.data.message || '获取地址列表失败');
}
}
} catch (error) {
console.error('加载地址列表失败:', error);
showError();
showToast('加载地址列表失败');
} finally {
isLoading = false;
}
}
// 显示加载状态
function showLoading() {
document.getElementById('loading').classList.remove('hidden');
document.getElementById('error').classList.add('hidden');
document.getElementById('empty').classList.add('hidden');
document.getElementById('addressList').classList.add('hidden');
}
// 显示错误状态
function showError() {
document.getElementById('loading').classList.add('hidden');
document.getElementById('error').classList.remove('hidden');
document.getElementById('empty').classList.add('hidden');
document.getElementById('addressList').classList.add('hidden');
}
// 显示地址列表
function displayAddresses() {
const loadingEl = document.getElementById('loading');
const errorEl = document.getElementById('error');
const emptyEl = document.getElementById('empty');
const listEl = document.getElementById('addressList');
loadingEl.classList.add('hidden');
errorEl.classList.add('hidden');
if (addresses.length === 0) {
emptyEl.classList.remove('hidden');
listEl.classList.add('hidden');
return;
}
listEl.innerHTML = addresses.map(address => `
<div class="address-item" data-id="${address.id}">
<div class="address-header">
<div class="user-info">
${address.name} ${address.phone}
</div>
${address.isDefault ? '<span class="default-tag">默认</span>' : ''}
</div>
<div class="address-detail">
${address.provinceName}${address.cityName}${address.districtName}${address.detailAddress}
</div>
<div class="address-actions">
<button class="action-btn" onclick="editAddress(${address.id})">编辑</button>
<button class="action-btn" onclick="deleteAddress(${address.id})">删除</button>
${!address.isDefault ? `<button class="action-btn primary" onclick="setDefault(${address.id})">设为默认</button>` : ''}
</div>
</div>
`).join('');
emptyEl.classList.add('hidden');
listEl.classList.remove('hidden');
}
// 添加地址
function addAddress() {
showToast('跳转到添加地址页面');
// 实际应用中这里应该跳转到添加地址页面
// window.location.href = '/pages/user/address/edit/index.html';
}
// 编辑地址
function editAddress(id) {
showToast(`编辑地址 ID: ${id}`);
// 实际应用中这里应该跳转到编辑地址页面
// window.location.href = `/pages/user/address/edit/index.html?id=${id}`;
}
// 删除地址
async function deleteAddress(id) {
if (!confirm('确定要删除这个地址吗?')) {
return;
}
try {
const res = await wxRequest({
url: `${config.apiBase}/users/addresses/${id}`,
method: 'DELETE'
});
if (res.statusCode === 200 && res.data.code === 200) {
showToast('删除成功');
// 从本地数组中移除
addresses = addresses.filter(addr => addr.id !== id);
displayAddresses();
} else {
throw new Error(res.data.message || '删除失败');
}
} catch (error) {
console.error('删除地址失败:', error);
showToast('删除失败');
}
}
// 设为默认地址
async function setDefault(id) {
try {
const res = await wxRequest({
url: `${config.apiBase}/users/addresses/${id}/default`,
method: 'PUT'
});
if (res.statusCode === 200 && res.data.code === 200) {
showToast('设置成功');
// 更新本地数据
addresses.forEach(addr => {
addr.isDefault = addr.id === id;
});
displayAddresses();
} else {
throw new Error(res.data.message || '设置失败');
}
} catch (error) {
console.error('设置默认地址失败:', error);
showToast('设置失败');
}
}
// 测试功能生成测试token
function generateTestToken() {
// 使用我们之前测试成功的token
const testToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX3R5cGUiOiJ1c2VyIiwiaXNzIjoiZGlhbnNoYW5nIiwiZXhwIjoxNzYwMDMzMjg2LCJuYmYiOjE3NjAwMjYwODYsImlhdCI6MTc2MDAyNjA4Nn0.zCPYwDld_WDSwySyj62CWgk9xJnOUhUt3NbTc6kL4Zg';
localStorage.setItem('token', testToken);
showToast('测试token已生成页面将自动刷新');
// 自动刷新页面以加载地址数据
setTimeout(() => {
loadAddresses();
}, 1000);
}
// 切换模拟模式
function toggleMock() {
config.useMock = !config.useMock;
showToast(`已切换到${config.useMock ? '模拟' : '真实API'}模式`);
loadAddresses();
}
</script>
</body>
</html>

View File

@@ -0,0 +1,463 @@
/* eslint-disable no-param-reassign */
import { fetchDeliveryAddressList, deleteAddress, setDefaultAddress } from '../../../../services/address/fetchAddress';
import Toast from 'tdesign-miniprogram/toast/index';
import { resolveAddress, rejectAddress } from '../../../../services/address/list';
import { getAddressPromise } from '../../../../services/address/edit';
// 添加日志工具
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);
}
};
Page({
data: {
addressList: [],
deleteID: '',
showDeleteConfirm: false,
isOrderSure: false,
},
/** 选择模式 */
selectMode: false,
/** 是否已经选择地址不置为true的话页面离开时会触发取消选择行为 */
hasSelect: false,
addressUpdated: false, // 标记地址是否被更新
onLoad(query) {
logger.info('ADDRESS_LIST_PAGE', '地址列表页面加载', { query });
const { selectMode = '', isOrderSure = '', id = '' } = query;
this.setData({
isOrderSure: !!isOrderSure,
id,
});
this.selectMode = !!selectMode;
this.addressUpdated = false; // 重置地址更新标记
logger.debug('ADDRESS_LIST_PAGE', '页面参数设置完成', {
selectMode: this.selectMode,
isOrderSure: !!isOrderSure,
id
});
this.init();
this.waitForNewAddress();
},
init() {
logger.info('ADDRESS_LIST_PAGE', '初始化地址列表页面');
this.getAddressList();
},
onShow() {
logger.info('ADDRESS_LIST_PAGE', '页面显示,刷新地址列表');
// 每次页面显示时都重新获取地址列表,确保数据是最新的
this.getAddressList();
},
onUnload() {
if (this.selectMode && !this.hasSelect) {
logger.info('ADDRESS_LIST_PAGE', '页面卸载,检查是否需要传递更新后的地址');
// 检查是否有默认地址,如果有则传递给订单确认页面
const defaultAddress = this.data.addressList.find(addr => addr.isDefault === 1);
if (defaultAddress && this.addressUpdated) {
logger.info('ADDRESS_LIST_PAGE', '传递更新后的默认地址给订单确认页面', {
addressId: defaultAddress.addressId,
name: defaultAddress.name
});
// 将默认地址存储到本地存储供订单确认页面的onShow方法使用
wx.setStorageSync('selectedAddress', defaultAddress);
return; // 不调用rejectAddress让订单确认页面通过onShow处理
}
rejectAddress();
}
},
getAddressList() {
logger.info('ADDRESS_LIST_PAGE', '开始获取地址列表');
const { id } = this.data;
fetchDeliveryAddressList().then((addressList) => {
logger.info('ADDRESS_LIST_PAGE', '获取地址列表成功', {
count: addressList.length,
addressIds: addressList.map(addr => addr.id)
});
// 转换API数据格式为前端期望的格式
const formattedList = addressList.map((address) => {
const formatted = {
id: address.id,
addressId: address.id,
name: address.name,
phoneNumber: address.phone,
address: `${address.province_name || ''}${address.city_name || ''}${address.district_name || ''}${address.detail_address || ''}`,
provinceName: address.province_name,
cityName: address.city_name,
districtName: address.district_name,
detailAddress: address.detail_address,
isDefault: address.is_default ? 1 : 0,
tag: address.address_tag || '',
};
logger.debug('ADDRESS_LIST_PAGE', '格式化地址数据', {
originalId: address.id,
formattedId: formatted.id,
name: formatted.name,
isDefault: formatted.isDefault
});
return formatted;
});
this.setData({
addressList: formattedList,
});
logger.info('ADDRESS_LIST_PAGE', '地址列表数据设置完成', {
totalCount: formattedList.length,
defaultCount: formattedList.filter(addr => addr.isDefault === 1).length
});
}).catch((err) => {
logger.error('ADDRESS_LIST_PAGE', '获取地址列表失败', { error: err.message || err });
Toast({
context: this,
selector: '#t-toast',
message: '获取地址列表失败',
icon: '',
duration: 1000,
});
});
},
getWXAddressHandle() {
console.log('[地址列表-微信导入] 开始获取微信地址');
wx.chooseAddress({
success: (res) => {
console.log('[地址列表-微信导入] wx.chooseAddress成功回调');
console.log('[地址列表-微信导入] 微信返回的原始数据:', res);
console.log('[地址列表-微信导入] errMsg:', res.errMsg);
if (res.errMsg.indexOf('ok') === -1) {
console.log('[地址列表-微信导入] errMsg检查失败显示错误信息');
Toast({
context: this,
selector: '#t-toast',
message: res.errMsg,
icon: '',
duration: 1000,
});
return;
}
console.log('[地址列表-微信导入] errMsg检查通过开始处理地址数据');
const { length: len } = this.data.addressList;
console.log('[地址列表-微信导入] 当前地址列表长度:', len);
const newAddress = {
name: res.userName,
phoneNumber: res.telNumber,
address: `${res.provinceName}${res.cityName}${res.countryName}${res.detailInfo}`,
isDefault: 0,
tag: '微信地址',
id: len,
};
console.log('[地址列表-微信导入] 构建的新地址对象:', newAddress);
this.setData({
[`addressList[${len}]`]: newAddress,
});
console.log('[地址列表-微信导入] 地址已添加到列表,新列表长度:', len + 1);
Toast({
context: this,
selector: '#t-toast',
message: '添加成功',
icon: '',
duration: 1000,
});
console.log('[地址列表-微信导入] 微信地址导入完成');
},
fail: (err) => {
console.error('[地址列表-微信导入] wx.chooseAddress失败:', err);
console.log('[地址列表-微信导入] 失败原因:', err.errMsg);
},
complete: () => {
console.log('[地址列表-微信导入] wx.chooseAddress调用完成');
}
});
},
confirmDeleteHandle({ detail }) {
const { id } = detail || {};
if (id !== undefined) {
this.setData({ deleteID: id, showDeleteConfirm: true });
Toast({
context: this,
selector: '#t-toast',
message: '地址删除成功',
theme: 'success',
duration: 1000,
});
} else {
Toast({
context: this,
selector: '#t-toast',
message: '需要组件库发新版才能拿到地址ID',
icon: '',
duration: 1000,
});
}
},
deleteAddressHandle(e) {
const { id } = e.currentTarget.dataset;
logger.info('ADDRESS_LIST_PAGE', '开始删除地址', { addressId: id });
// 调用API删除地址
deleteAddress(id).then(() => {
logger.info('ADDRESS_LIST_PAGE', '删除地址成功', { addressId: id });
// 删除成功后从列表中移除
this.setData({
addressList: this.data.addressList.filter((address) => address.id !== id),
deleteID: '',
showDeleteConfirm: false,
});
Toast({
context: this,
selector: '#t-toast',
message: '地址删除成功',
theme: 'success',
duration: 1000,
});
}).catch((err) => {
logger.error('ADDRESS_LIST_PAGE', '删除地址失败', {
addressId: id,
error: err.message || err
});
console.error('删除地址失败:', err);
Toast({
context: this,
selector: '#t-toast',
message: '删除地址失败',
icon: '',
duration: 1000,
});
// 关闭确认对话框
this.setData({
deleteID: '',
showDeleteConfirm: false,
});
});
},
editAddressHandle({ detail }) {
logger.info('ADDRESS_LIST_PAGE', '编辑地址', { addressDetail: detail });
this.waitForNewAddress();
const { id } = detail || {};
wx.navigateTo({ url: `/pages/user/address/edit/index?id=${id}` });
},
selectHandle({ detail }) {
logger.info('ADDRESS_LIST_PAGE', '选择地址', {
selectMode: this.selectMode,
addressDetail: detail
});
if (this.selectMode) {
this.hasSelect = true;
// 将选择的地址存储到本地存储中,供订单确认页面使用
wx.setStorageSync('selectedAddress', detail);
logger.info('ADDRESS_LIST_PAGE', '地址已存储到本地存储', { selectedAddress: detail });
resolveAddress(detail);
wx.navigateBack({ delta: 1 });
} else {
this.editAddressHandle({ detail });
}
},
createHandle() {
logger.info('ADDRESS_LIST_PAGE', '创建新地址');
this.waitForNewAddress();
wx.navigateTo({ url: '/pages/user/address/edit/index' });
},
setDefaultAddressHandle({ detail }) {
logger.info('ADDRESS_LIST_PAGE', '设置默认地址', { addressDetail: detail });
const addressId = parseInt(detail.id || detail.addressId);
if (!addressId) {
logger.error('ADDRESS_LIST_PAGE', '地址ID无效', { detail });
Toast({
context: this,
selector: '#t-toast',
message: '地址ID无效',
icon: '',
duration: 1000,
});
return;
}
// 调用设置默认地址API
setDefaultAddress(addressId)
.then(() => {
logger.info('ADDRESS_LIST_PAGE', '设置默认地址成功', { addressId });
Toast({
context: this,
selector: '#t-toast',
message: '设置默认地址成功',
icon: '',
duration: 1000,
});
// 更新本地地址列表
const addressList = this.data.addressList.map(address => ({
...address,
isDefault: (parseInt(address.id) === addressId || parseInt(address.addressId) === addressId) ? 1 : 0
}));
// 重新排序,默认地址排在前面
addressList.sort((prevAddress, nextAddress) => {
if (prevAddress.isDefault && !nextAddress.isDefault) {
return -1;
}
if (!prevAddress.isDefault && nextAddress.isDefault) {
return 1;
}
return 0;
});
this.setData({
addressList: addressList,
});
logger.info('ADDRESS_LIST_PAGE', '地址列表已更新', {
totalCount: addressList.length,
defaultAddressId: addressId
});
})
.catch((err) => {
logger.error('ADDRESS_LIST_PAGE', '设置默认地址失败', {
addressId,
error: err.message || err
});
Toast({
context: this,
selector: '#t-toast',
message: '设置默认地址失败',
icon: '',
duration: 1000,
});
});
},
waitForNewAddress() {
logger.debug('ADDRESS_LIST_PAGE', '等待新地址返回');
getAddressPromise()
.then((newAddress) => {
logger.info('ADDRESS_LIST_PAGE', '收到新地址数据', {
addressId: newAddress.addressId,
name: newAddress.name,
isEdit: newAddress.isEdit
});
let addressList = [...this.data.addressList];
newAddress.phoneNumber = newAddress.phone;
newAddress.address = `${newAddress.provinceName}${newAddress.cityName}${newAddress.districtName}${newAddress.detailAddress}`;
newAddress.tag = newAddress.addressTag;
if (!newAddress.addressId) {
logger.debug('ADDRESS_LIST_PAGE', '添加新地址到列表');
newAddress.id = `${addressList.length}`;
newAddress.addressId = `${addressList.length}`;
if (newAddress.isDefault === 1) {
logger.debug('ADDRESS_LIST_PAGE', '新地址设为默认,清除其他默认地址');
addressList = addressList.map((address) => {
address.isDefault = 0;
return address;
});
} else {
newAddress.isDefault = 0;
}
addressList.push(newAddress);
} else {
logger.debug('ADDRESS_LIST_PAGE', '更新现有地址');
addressList = addressList.map((address) => {
if (address.addressId === newAddress.addressId) {
return newAddress;
}
return address;
});
}
addressList.sort((prevAddress, nextAddress) => {
if (prevAddress.isDefault && !nextAddress.isDefault) {
return -1;
}
if (!prevAddress.isDefault && nextAddress.isDefault) {
return 1;
}
return 0;
});
this.setData({
addressList: addressList,
});
// 标记地址已被更新
this.addressUpdated = true;
logger.info('ADDRESS_LIST_PAGE', '地址列表更新完成', {
totalCount: addressList.length,
defaultCount: addressList.filter(addr => addr.isDefault === 1).length,
addressUpdated: true
});
})
.catch((e) => {
if (e.message !== 'cancel') {
logger.error('ADDRESS_LIST_PAGE', '地址编辑发生错误', { error: e.message || e });
Toast({
context: this,
selector: '#t-toast',
message: '地址编辑发生错误',
icon: '',
duration: 1000,
});
} else {
logger.info('ADDRESS_LIST_PAGE', '用户取消地址编辑');
}
});
},
});

View File

@@ -0,0 +1,11 @@
{
"navigationBarTitleText": "收货地址",
"usingComponents": {
"t-icon": "tdesign-miniprogram/icon/icon",
"t-image": "/components/webp-image/index",
"t-toast": "tdesign-miniprogram/toast/toast",
"t-address-item": "/pages/user/components/ui-address-item/index",
"t-location": "/pages/user/components/t-location/index",
"t-empty": "tdesign-miniprogram/empty/empty"
}
}

View File

@@ -0,0 +1,40 @@
<view class="address-container">
<view class="address-list" wx:if="{{addressList.length > 0}}">
<block wx:for="{{addressList}}" wx:for-index="index" wx:for-item="address" wx:key="addressId">
<t-address-item
isDrawLine="{{index+1 !== addressList.length}}"
extra-space="{{extraSpace}}"
class-prefix="ym"
address="{{address}}"
data-id="{{address.id}}"
bind:onSelect="selectHandle"
bind:onDelete="deleteAddressHandle"
bind:onEdit="editAddressHandle"
bind:onSetDefault="setDefaultAddressHandle"
/>
</block>
</view>
<view wx:else class="no-address">
<t-empty icon="" description="暂无收货地址,赶快添加吧" />
</view>
<view class="bottom-fixed">
<view class="btn-wrap">
<t-location
title="微信地址导入"
isOrderSure="{{isOrderSure}}"
isDisabledBtn="{{addressList.length >= 20}}"
navigateUrl="/pages/user/address/edit/index"
navigateEvent="onWeixinAddressPassed"
t-class="location-btn"
isCustomStyle="{{true}}"
bind:navigate="waitForNewAddress"
/>
<view class="address-btn {{addressList.length >= 20 ? 'btn-default':''}}" bind:tap="createHandle">
<t-icon name="add" size="48rpx" color="#fff" t-class="custom-class" />
<text>新建收货地址</text>
</view>
</view>
<view class="footer" wx:if="{{addressList.length >= 20}}">最多支持添加20个收货地址</view>
</view>
</view>
<t-toast id="t-toast" />

View File

@@ -0,0 +1,109 @@
page {
background: #f5f5f5;
height: 100%;
}
.address-container {
display: flex;
flex-direction: column;
align-items: stretch;
padding-bottom: calc(env(safe-area-inset-bottom) + 172rpx);
}
.address-container .address-list {
font-size: 24rpx;
background-color: #ffffff;
-webkit-overflow-scrolling: touch;
}
.address-list .no-address {
width: 750rpx;
padding-top: 30vh;
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
}
.address-list .no-address__icon {
width: 224rpx;
height: 224rpx;
}
.address-list .no-address__text {
font-size: 28rpx;
line-height: 40rpx;
color: #999999;
margin-top: 24rpx;
}
.address-container .bottom-fixed {
border-top: 1rpx solid #e5e5e5;
position: fixed;
bottom: 0;
left: 0;
right: 0;
z-index: 1000;
background: #fff;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
padding: 12rpx 32rpx calc(env(safe-area-inset-bottom) + 12rpx) 32rpx;
}
.address-container .btn-wrap {
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 32rpx;
font-weight: bold;
}
.address-container .btn-wrap .location-btn {
width: 332rpx;
height: 88rpx;
display: flex;
justify-content: center;
align-items: center;
background-color: #ffffff;
color: #333;
position: relative;
}
.address-container .btn-wrap .location-btn::after {
content: '';
position: absolute; /* 把父视图设置为relative方便定位*/
top: 0;
left: 0;
width: 200%;
height: 200%;
transform: scale(0.5);
transform-origin: 0 0;
box-sizing: border-box;
border-radius: 88rpx;
border: #dddddd 2rpx solid;
}
.address-container .btn-wrap .address-btn {
width: 332rpx;
height: 88rpx;
display: flex;
justify-content: center;
align-items: center;
background-color: #fa4126;
border-radius: 44rpx;
color: #fff;
}
.address-container .btn-wrap .btn-default {
background: #c6c6c6;
}
.address-container .bottom-fixed .footer {
margin-top: 10rpx;
display: inline-block;
width: 100%;
text-align: center;
font-size: 24rpx;
font-weight: 400;
color: #ff2525;
line-height: 60rpx;
height: 60rpx;
}
.address-container .message {
margin-top: 48rpx;
}
.address-container .custom-class {
margin-right: 12rpx;
font-weight: normal;
}

View File

@@ -0,0 +1,158 @@
import { getPermission } from '../../../../utils/getPermission';
import Toast from 'tdesign-miniprogram/toast/index';
import { addressParse } from '../../../../utils/addressParse';
import { resolveAddress, rejectAddress } from '../../../../services/address/list';
Component({
externalClasses: ['t-class'],
properties: {
title: {
type: String,
},
navigateUrl: {
type: String,
},
navigateEvent: {
type: String,
},
isCustomStyle: {
type: Boolean,
value: false,
},
isDisabledBtn: {
type: Boolean,
value: false,
},
isOrderSure: {
type: Boolean,
value: false,
},
},
methods: {
getWxLocation() {
console.log('[微信地址导入] 开始获取微信地址');
console.log('[微信地址导入] 按钮状态检查:', {
isDisabledBtn: this.properties.isDisabledBtn,
isOrderSure: this.properties.isOrderSure,
navigateUrl: this.properties.navigateUrl
});
if (this.properties.isDisabledBtn) {
console.log('[微信地址导入] 按钮被禁用,退出');
return;
}
console.log('[微信地址导入] 开始获取通讯地址权限');
getPermission({ code: 'scope.address', name: '通讯地址' }).then(() => {
console.log('[微信地址导入] 权限获取成功调用wx.chooseAddress');
wx.chooseAddress({
success: async (options) => {
console.log('[微信地址导入] wx.chooseAddress成功回调');
console.log('[微信地址导入] 原始地址数据:', options);
const { provinceName, cityName, countyName, detailInfo, userName, telNumber } = options;
console.log('[微信地址导入] 解析后的地址字段:', {
provinceName,
cityName,
countyName,
detailInfo,
userName,
telNumber
});
// 移除手机号验证逻辑,允许导入任何格式的手机号
console.log('[微信地址导入] 跳过手机号验证,直接使用微信提供的手机号:', telNumber);
const target = {
name: userName,
phone: telNumber,
countryName: '中国',
countryCode: 'chn',
detailAddress: detailInfo,
provinceName: provinceName,
cityName: cityName,
districtName: countyName,
isDefault: false,
isOrderSure: this.properties.isOrderSure,
};
console.log('[微信地址导入] 构建目标地址对象:', target);
try {
console.log('[微信地址导入] 开始地址解析:', { provinceName, cityName, countyName });
const { provinceCode, cityCode, districtCode } = await addressParse(provinceName, cityName, countyName);
console.log('[微信地址导入] 地址解析成功:', { provinceCode, cityCode, districtCode });
const params = Object.assign(target, {
provinceCode,
cityCode,
districtCode,
});
console.log('[微信地址导入] 最终地址参数:', params);
if (this.properties.isOrderSure) {
console.log('[微信地址导入] 订单确认模式调用onHandleSubmit');
this.onHandleSubmit(params);
} else if (this.properties.navigateUrl != '') {
console.log('[微信地址导入] 导航模式,跳转到:', this.properties.navigateUrl);
const { navigateEvent } = this.properties;
this.triggerEvent('navigate');
wx.navigateTo({
url: this.properties.navigateUrl,
success: function (res) {
console.log('[微信地址导入] 页面跳转成功,发送事件:', navigateEvent);
res.eventChannel.emit(navigateEvent, params);
},
});
} else {
console.log('[微信地址导入] 触发change事件');
this.triggerEvent('change', params);
}
} catch (error) {
console.error('[微信地址导入] 地址解析失败:', error);
wx.showToast({ title: '地址解析出错,请稍后再试', icon: 'none' });
}
},
fail(err) {
console.warn('[微信地址导入] 用户取消选择或选择失败:', err);
},
});
}).catch((error) => {
console.error('[微信地址导入] 权限获取失败:', error);
});
},
async queryAddress(addressId) {
try {
const { data } = await apis.userInfo.queryAddress({ addressId });
return data.userAddressVO;
} catch (err) {
console.error('查询地址错误', err);
throw err;
}
},
findPage(pageRouteUrl) {
const currentRoutes = getCurrentPages().map((v) => v.route);
return currentRoutes.indexOf(pageRouteUrl);
},
async onHandleSubmit(params) {
try {
const orderPageDeltaNum = this.findPage('pages/order/order-confirm/index');
if (orderPageDeltaNum > -1) {
wx.navigateBack({ delta: 1 });
resolveAddress(params);
return;
}
} catch (err) {
rejectAddress(params);
console.error(err);
}
},
},
});

View File

@@ -0,0 +1,8 @@
{
"component": true,
"usingComponents": {
"t-cell": "tdesign-miniprogram/cell/cell",
"t-icon": "tdesign-miniprogram/icon/icon",
"t-toast": "tdesign-miniprogram/toast/toast"
}
}

View File

@@ -0,0 +1,16 @@
<view class="wx-address t-class" bind:tap="getWxLocation">
<block wx:if="{{isCustomStyle}}">
<view class="wx-address-custom">
<t-icon prefix="wr" t-class="weixin" color="#0ABF5B" name="wechat" size="48rpx" />
<text>{{title}}</text>
</view>
<slot />
</block>
<block wx:else>
<t-cell title="{{title}}" title-class="cell__title" wr-class="cell" border="{{false}}">
<t-icon t-class="weixin" slot="icon" color="#0ABF5B" name="logo-windows" size="48rpx" />
<t-icon slot="right-icon" name="chevron-right" class="custom-icon" color="#bbb" />
</t-cell>
</block>
</view>
<t-toast id="t-toast" />

View File

@@ -0,0 +1,19 @@
.wx-address .weixin {
display: inline-block;
font-size: 48rpx !important;
margin-right: 20rpx;
font-weight: normal;
}
.wx-address .cell {
padding: 32rpx 30rpx;
border-radius: 8rpx;
}
.wx-address .cell__title {
font-size: 30rpx;
color: #333333;
}
.wx-address-custom {
display: flex;
align-items: center;
font-size: 32rpx;
}

View File

@@ -0,0 +1,50 @@
Component({
options: {
addGlobalClass: true,
multipleSlots: true,
},
properties: {
address: {
type: Object,
value: {},
},
customIcon: {
type: String,
value: 'edit-1',
},
extraSpace: {
type: Boolean,
value: true,
},
isDrawLine: {
type: Boolean,
value: true,
},
},
externalClasses: [
'item-wrapper-class',
'title-class',
'default-tag-class',
'normal-tag-class',
'address-info-class',
'delete-class',
],
methods: {
onDelete(e) {
const { item } = e.currentTarget.dataset;
this.triggerEvent('onDelete', item);
},
onSelect(e) {
const { item } = e.currentTarget.dataset;
this.triggerEvent('onSelect', item);
},
onEdit(e) {
const { item } = e.currentTarget.dataset;
this.triggerEvent('onEdit', item);
},
onSetDefault(e) {
const { item } = e.currentTarget.dataset;
this.triggerEvent('onSetDefault', item);
},
},
});

View File

@@ -0,0 +1,8 @@
{
"component": true,
"usingComponents": {
"t-icon": "tdesign-miniprogram/icon/icon",
"t-tag": "tdesign-miniprogram/tag/tag",
"t-swipe-cell": "tdesign-miniprogram/swipe-cell/swipe-cell"
}
}

View File

@@ -0,0 +1,37 @@
<wxs module="phoneReg">
var toHide = function(array) { var mphone = array.substring(0, 3) + '****' + array.substring(7); return mphone; }
module.exports.toHide = toHide;
</wxs>
<view class="address-item-wrapper item-wrapper-class">
<t-swipe-cell class="swipe-out">
<view class="address {{isDrawLine ? 'draw-line' : ''}}" bindtap="onSelect" data-item="{{address}}">
<view class="address-left" wx:if="{{extraSpace}}">
<t-icon wx:if="{{address.checked}}" name="check" color="#FA4126" class-prefix="{{classPrefix}}" size="46rpx" />
</view>
<view class="address-content">
<view class="title title-class">
<text class="text-style">{{address.name}}</text>
<text>{{phoneReg.toHide(address.phoneNumber || '')}}</text>
</view>
<view class="label-adds">
<text class="adds address-info-class">
<text wx:if="{{address.isDefault === 1}}" class="tag tag-default default-tag-class">默认</text>
<text wx:if="{{address.tag}}" class="tag tag-primary normal-tag-class">{{address.tag}}</text>
<text class="address-text">{{address.address}}</text>
</text>
</view>
</view>
<view catch:tap="onEdit" data-item="{{address}}" class="address-edit">
<t-icon name="{{customIcon}}" class-prefix="{{classPrefix}}" size="46rpx" color="#BBBBBB" />
</view>
</view>
<view slot="right" class="swipe-right-actions">
<view wx:if="{{address.isDefault !== 1}}" class="swipe-action-btn set-default-btn" bindtap="onSetDefault" data-item="{{address}}">
设为默认
</view>
<view class="swipe-action-btn delete-btn delete-class" bindtap="onDelete" data-item="{{address}}">
删除
</view>
</view>
</t-swipe-cell>
</view>

View File

@@ -0,0 +1,115 @@
.address-item-wrapper {
overflow: hidden;
}
.address-item-wrapper .swipe-out .wr-swiper-cell {
margin-top: 20rpx;
}
.address-item-wrapper .swipe-out .swipe-right-actions {
display: flex;
height: 100%;
}
.address-item-wrapper .swipe-out .swipe-action-btn {
display: flex;
justify-content: center;
align-items: center;
width: 144rpx;
height: 100%;
color: #fff;
font-size: 28rpx;
line-height: 40rpx;
}
.address-item-wrapper .swipe-out .set-default-btn {
background-color: #07c160;
}
.address-item-wrapper .swipe-out .delete-btn {
background-color: #fa4126;
}
.address-item-wrapper .draw-line {
position: relative;
}
.address-item-wrapper .draw-line::after {
content: '';
position: absolute;
bottom: 0;
left: 32rpx;
width: 200%;
height: 2rpx;
transform: scale(0.5);
transform-origin: 0 0;
box-sizing: border-box;
border-bottom: #e5e5e5 2rpx solid;
}
.address-item-wrapper .address {
display: flex;
justify-content: space-between;
align-items: center;
padding: 32rpx;
background-color: #fff;
}
.address-item-wrapper .address .address-edit {
padding: 20rpx 0 20rpx 46rpx;
}
.address-item-wrapper .address .address-left {
width: 80rpx;
display: flex;
justify-content: center;
}
.address-item-wrapper .address .address-content {
display: flex;
flex-direction: column;
flex: 1;
}
.address-item-wrapper .address .address-content .title {
font-size: 32rpx;
line-height: 48rpx;
margin-bottom: 16rpx;
color: #333333;
font-weight: bold;
display: flex;
}
.address-item-wrapper .address .address-content .title .text-style {
margin-right: 8rpx;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 280rpx;
}
.address-item-wrapper .address .address-content .label-adds {
display: flex;
}
.address-item-wrapper .address .address-content .label-adds .adds {
display: -webkit-box;
overflow: hidden;
text-overflow: ellipsis;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
color: #999999;
}
.address-item-wrapper .address .address-content .label-adds .tag {
display: inline-block;
padding: 0rpx 8rpx;
min-width: 40rpx;
height: 32rpx;
border-radius: 18rpx;
font-size: 20rpx;
line-height: 32rpx;
text-align: center;
margin-right: 8rpx;
vertical-align: text-top;
}
.address-item-wrapper .address .address-content .label-adds .tag-default {
background: #ffece9;
color: #fa4126;
}
.address-item-wrapper .address .address-content .label-adds .tag-primary {
background: #f0f1ff;
color: #5a66ff;
}
.address-item-wrapper .address .address-content .label-adds .address-text {
font-size: 28rpx;
line-height: 40rpx;
color: #999999;
}

View File

@@ -0,0 +1,19 @@
Page({
data: {
nameValue: '',
},
onLoad(options) {
const { name } = options;
this.setData({
nameValue: name,
});
},
onSubmit() {
wx.navigateBack({ backRefresh: true });
},
clearContent() {
this.setData({
nameValue: '',
});
},
});

View File

@@ -0,0 +1,8 @@
{
"navigationBarTitleText": "昵称",
"usingComponents": {
"t-input": "tdesign-miniprogram/input/input",
"t-icon": "tdesign-miniprogram/icon/icon",
"t-button": "tdesign-miniprogram/button/button"
}
}

View File

@@ -0,0 +1,14 @@
<view class="name-edit">
<t-input
borderless
model:value="{{nameValue}}"
placeholder="请输入文字"
label="昵称"
clearable
bind:clear="clearContent"
/>
<view class="name-edit__input--desc"> 最多可输入15个字 </view>
<view class="name-edit__wrapper">
<t-button block shape="round" disabled="{{!nameValue}}" bind:tap="onSubmit">保存</t-button>
</view>
</view>

View File

@@ -0,0 +1,18 @@
page {
background-color: #f5f5f5;
}
page view {
box-sizing: border-box;
}
.name-edit {
padding-top: 20rpx;
}
.name-edit .name-edit__input--desc {
font-size: 26rpx;
padding: 16rpx 32rpx;
color: #999;
margin-bottom: 200rpx;
}
.name-edit .name-edit__wrapper {
margin: 0 32rpx;
}

View File

@@ -0,0 +1,540 @@
import { fetchPerson } from '../../../services/usercenter/fetchPerson';
import { phoneEncryption } from '../../../utils/util';
import Toast from 'tdesign-miniprogram/toast/index';
const weChatAuthService = require('../../../services/auth/wechat');
Page({
data: {
personInfo: {
avatarUrl: '',
nickName: '',
gender: 0, // 默认为0未设置
phoneNumber: '',
level: 1
},
originalPersonInfo: null, // 保存原始数据
displayPhoneNumber: '', // 用于显示的加密手机号
defaultAvatarUrl: 'https://tdesign.gtimg.com/miniprogram/template/retail/usercenter/icon-user-center-avatar@2x.png',
genderVisible: false,
genderList: [
{ label: '男', value: 1 },
{ label: '女', value: 2 },
{ label: '未设置', value: 0 }
],
// 性别映射
genderMap: {
0: '未设置',
1: '男',
2: '女'
},
saving: false
},
onLoad() {
this.init();
},
init() {
this.fetchData();
},
fetchData() {
console.log('=== 开始获取用户信息 ===');
fetchPerson().then((personInfo) => {
console.log('从API获取到的原始用户信息:', personInfo);
// 确保所有字段都有正确的类型和默认值
const safePersonInfo = {
avatarUrl: personInfo.avatarUrl || '',
nickName: personInfo.nickName || '',
gender: personInfo.gender || 0,
phoneNumber: personInfo.phoneNumber || '',
level: personInfo.level || 1,
};
console.log('处理后的安全用户信息:', safePersonInfo);
console.log('性别数据详细信息:', {
原始性别: personInfo.gender,
处理后性别: safePersonInfo.gender,
性别类型: typeof safePersonInfo.gender
});
console.log('手机号数据详细信息:', {
原始手机号: personInfo.phoneNumber,
处理后手机号: safePersonInfo.phoneNumber,
手机号类型: typeof safePersonInfo.phoneNumber
});
console.log('个人资料页 - 头像URL:', safePersonInfo.avatarUrl);
console.log('个人资料页 - 默认头像URL:', this.data.defaultAvatarUrl);
// 保存原始数据用于编辑,显示数据用于界面展示
this.setData({
personInfo: safePersonInfo,
originalPersonInfo: JSON.parse(JSON.stringify(safePersonInfo)), // 深拷贝保存原始数据
originalNickname: safePersonInfo.nickName, // 保存原始昵称用于重置
displayPhoneNumber: phoneEncryption(safePersonInfo.phoneNumber), // 仅用于显示的加密手机号
});
console.log('设置到页面数据后的personInfo:', this.data.personInfo);
console.log('原始数据originalPersonInfo:', this.data.originalPersonInfo);
}).catch((error) => {
console.error('获取用户信息失败:', error);
Toast({
context: this,
selector: '#t-toast',
message: '获取用户信息失败',
theme: 'error',
});
});
},
onClickCell({ currentTarget }) {
const { dataset } = currentTarget;
const { nickName } = this.data.personInfo;
switch (dataset.type) {
case 'name':
wx.navigateTo({
url: `/pages/user/name-edit/index?name=${nickName}`,
});
break;
case 'avatarUrl':
this.toModifyAvatar();
break;
default: {
break;
}
}
},
// 保存性别设置
async saveGender(gender) {
this.setData({ saving: true });
try {
const userInfo = {
nickName: this.data.personInfo.nickName,
avatarUrl: this.data.personInfo.avatarUrl,
gender: gender
};
await weChatAuthService.updateUserProfile(userInfo);
this.setData({ saving: false });
Toast({
context: this,
selector: '#t-toast',
message: '性别设置成功',
theme: 'success',
});
} catch (error) {
console.error('保存性别失败:', error);
this.setData({ saving: false });
Toast({
context: this,
selector: '#t-toast',
message: '性别设置失败,请重试',
theme: 'error',
});
}
},
// 处理头像昵称组件的回调(微信官方组件)- 自动保存
async onChooseAvatar(e) {
const { avatarUrl } = e.detail;
console.log('从微信头像组件获取头像:', avatarUrl);
// 立即更新界面显示
this.setData({
'personInfo.avatarUrl': avatarUrl,
});
// 自动保存头像
await this.saveAvatar(avatarUrl);
},
// 保存头像
async saveAvatar(avatarUrl) {
this.setData({ saving: true });
try {
const userInfo = {
nickName: this.data.personInfo.nickName,
avatarUrl: avatarUrl,
gender: this.data.personInfo.gender
};
console.log('保存头像信息:', userInfo);
await weChatAuthService.updateUserProfile(userInfo);
// 确保头像URL已保存到本地数据
this.setData({
saving: false,
'personInfo.avatarUrl': avatarUrl
});
Toast({
context: this,
selector: '#t-toast',
message: '头像设置成功',
theme: 'success',
});
} catch (error) {
console.error('保存头像失败:', error);
this.setData({ saving: false });
Toast({
context: this,
selector: '#t-toast',
message: '头像设置失败,请重试',
theme: 'error',
});
}
},
// 昵称输入变化
onNicknameChange(e) {
console.log('昵称输入变化:', e.detail.value);
this.setData({
'personInfo.nickName': e.detail.value
});
},
// 保存昵称(兼容旧方式)
saveNickname(e) {
console.log('保存昵称事件触发:', e);
const nickname = e.detail.value || this.data.personInfo.nickName;
console.log('要保存的昵称:', nickname);
if (!nickname || nickname.trim() === '') {
wx.showToast({
title: '昵称不能为空',
icon: 'none'
});
return;
}
this.saveNicknameToServer(nickname.trim());
},
// 性别选择事件radio-group change事件
onGenderChange(e) {
const gender = parseInt(e.detail.value);
console.log('性别选择变化:', gender);
this.setData({
'personInfo.gender': gender
});
// 自动保存性别
this.saveGender(gender);
},
// 手机号获得焦点事件
onPhoneFocus(e) {
console.log('手机号输入框获得焦点');
// 确保显示原始手机号而不是加密的
if (this.data.originalPersonInfo && this.data.originalPersonInfo.phoneNumber) {
this.setData({
displayPhoneNumber: this.data.originalPersonInfo.phoneNumber
});
}
},
// 手机号输入事件(实时输入)
onPhoneInput(e) {
const phoneNumber = e.detail.value.trim();
// 更新显示数据和实际数据
this.setData({
displayPhoneNumber: phoneNumber,
'personInfo.phoneNumber': phoneNumber
});
// 清除之前的定时器
if (this.phoneInputTimer) {
clearTimeout(this.phoneInputTimer);
}
// 设置延迟自动保存用户停止输入1.5秒后自动保存)
this.phoneInputTimer = setTimeout(() => {
this.updatePhoneNumber(phoneNumber, 'auto');
}, 1500);
},
// 手机号输入失焦事件
onPhoneBlur(e) {
const phoneNumber = e.detail.value.trim();
// 清除定时器,立即保存
if (this.phoneInputTimer) {
clearTimeout(this.phoneInputTimer);
this.phoneInputTimer = null;
}
this.updatePhoneNumber(phoneNumber, 'blur');
// 失焦后显示加密的手机号
if (phoneNumber) {
this.setData({
displayPhoneNumber: phoneEncryption(phoneNumber)
});
}
},
// 手机号输入确认事件(回车)
onPhoneConfirm(e) {
const phoneNumber = e.detail.value.trim();
// 清除定时器,立即保存
if (this.phoneInputTimer) {
clearTimeout(this.phoneInputTimer);
this.phoneInputTimer = null;
}
this.updatePhoneNumber(phoneNumber, 'confirm');
},
// 更新手机号
updatePhoneNumber(phoneNumber, triggerType = 'manual') {
console.log(`=== 手机号更新触发 (${triggerType}) ===`);
console.log('输入的手机号:', phoneNumber);
// 如果手机号为空,直接保存(清空操作)
if (!phoneNumber) {
console.log('手机号为空,执行清空操作');
this.setData({
'personInfo.phoneNumber': phoneNumber
});
this.savePhoneNumber(phoneNumber, triggerType);
return;
}
// 验证手机号格式
if (!this.validatePhoneNumber(phoneNumber)) {
// 只在非自动触发时显示错误提示
if (triggerType !== 'auto') {
wx.showToast({
title: '手机号格式不正确',
icon: 'none'
});
}
console.log('手机号格式验证失败:', phoneNumber);
return;
}
// 检查是否与原始值相同,避免重复保存
const originalPhoneNumber = this.data.originalPersonInfo ? this.data.originalPersonInfo.phoneNumber : '';
if (phoneNumber === originalPhoneNumber) {
console.log('手机号未变化,跳过保存');
return;
}
// 更新数据
this.setData({
'personInfo.phoneNumber': phoneNumber
});
// 自动保存手机号
this.savePhoneNumber(phoneNumber, triggerType);
},
// 验证手机号格式
validatePhoneNumber(phoneNumber) {
const phoneRegex = /^1[3-9]\d{9}$/;
return phoneRegex.test(phoneNumber);
},
// 保存手机号
async savePhoneNumber(phoneNumber, triggerType = 'manual') {
if (this.data.saving) {
console.log('正在保存中,跳过重复请求');
return;
}
this.setData({ saving: true });
try {
console.log(`=== 开始保存手机号到服务器 (${triggerType}) ===`);
console.log('要保存的手机号:', phoneNumber);
// 构建用户信息对象,包含手机号
const userInfo = {
nickName: this.data.personInfo.nickName,
avatarUrl: this.data.personInfo.avatarUrl,
gender: this.data.personInfo.gender,
phoneNumber: phoneNumber // 添加手机号字段
};
console.log('发送到服务器的用户信息:', userInfo);
// 调用微信授权服务更新用户信息
const result = await weChatAuthService.updateUserProfile(userInfo);
console.log('服务器返回结果:', result);
// 根据触发方式显示不同的提示
if (triggerType === 'auto') {
// 自动保存时显示更简洁的提示
console.log('自动保存成功');
} else {
// 手动触发时显示Toast提示
wx.showToast({
title: phoneNumber ? '手机号保存成功' : '手机号已清空',
icon: 'success',
duration: 1500
});
}
// 保存成功后,立即更新原始数据
if (this.data.originalPersonInfo) {
this.setData({
'originalPersonInfo.phoneNumber': phoneNumber
});
}
// 重新获取用户信息验证是否真的更新了
console.log('=== 重新获取用户信息验证更新 ===');
this.fetchData();
} catch (error) {
console.error('保存手机号失败:', error);
// 只在非自动触发时显示错误提示
if (triggerType !== 'auto') {
wx.showToast({
title: '保存失败,请重试',
icon: 'none'
});
}
} finally {
this.setData({ saving: false });
}
},
// 保存昵称到服务器
async saveNicknameToServer(nickname) {
this.setData({ saving: true });
try {
console.log('=== 开始保存昵称到服务器 ===');
// 如果传入了昵称参数,使用传入的昵称;否则使用当前数据中的昵称
const finalNickname = nickname || this.data.personInfo.nickName;
console.log('要保存的昵称:', finalNickname);
console.log('当前数据中的昵称:', this.data.personInfo.nickName);
// 更新本地数据
if (nickname && nickname !== this.data.personInfo.nickName) {
this.setData({
'personInfo.nickName': nickname
});
}
const userInfo = {
nickName: finalNickname,
avatarUrl: this.data.personInfo.avatarUrl,
gender: this.data.personInfo.gender
};
console.log('发送到服务器的用户信息:', userInfo);
const result = await weChatAuthService.updateUserProfile(userInfo);
console.log('服务器返回结果:', result);
// 保存成功后,重新获取用户信息验证是否真的更新了
console.log('=== 重新获取用户信息验证更新 ===');
this.fetchData();
this.setData({ saving: false });
Toast({
context: this,
selector: '#t-toast',
message: '昵称设置成功',
theme: 'success',
});
} catch (error) {
console.error('保存昵称失败:', error);
this.setData({ saving: false });
Toast({
context: this,
selector: '#t-toast',
message: '昵称设置失败,请重试',
theme: 'error',
});
}
},
// 兼容旧版本的头像选择方式 - 自动保存
async toModifyAvatar() {
try {
const tempFilePath = await new Promise((resolve, reject) => {
wx.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: (res) => {
const { path, size } = res.tempFiles && res.tempFiles.length > 0 ? res.tempFiles[0] : {};
if (size <= 10485760) {
resolve(path);
} else {
reject({ errMsg: '图片大小超出限制,请重新上传' });
}
},
fail: (err) => reject(err),
});
});
// 更新本地显示
this.setData({
'personInfo.avatarUrl': tempFilePath,
});
// 自动保存头像
await this.saveAvatar(tempFilePath);
} catch (error) {
if (error.errMsg === 'chooseImage:fail cancel') return;
Toast({
context: this,
selector: '#t-toast',
message: error.errMsg || error.msg || '选择头像出错了',
theme: 'error',
});
}
},
// 切换账号登录
openUnbindConfirm() {
wx.showModal({
title: '切换账号',
content: '确定要切换到其他微信账号登录吗?',
success: (res) => {
if (res.confirm) {
// 清除本地存储的用户信息
wx.removeStorageSync('token');
wx.removeStorageSync('userInfo');
// 跳转到登录页面
wx.reLaunch({
url: '/pages/login/index'
});
}
}
});
},
// 页面卸载时清理定时器
onUnload() {
if (this.phoneInputTimer) {
clearTimeout(this.phoneInputTimer);
this.phoneInputTimer = null;
console.log('页面卸载,清理手机号输入定时器');
}
}
});

View File

@@ -0,0 +1,16 @@
{
"navigationBarTitleText": "个人资料",
"usingComponents": {
"t-cell-group": "tdesign-miniprogram/cell-group/cell-group",
"t-cell": "tdesign-miniprogram/cell/cell",
"t-button": "tdesign-miniprogram/button/button",
"t-avatar": "tdesign-miniprogram/avatar/avatar",
"t-image": "/components/webp-image/index",
"t-dialog": "tdesign-miniprogram/dialog/dialog",
"t-toast": "tdesign-miniprogram/toast/toast",
"t-picker": "tdesign-miniprogram/picker/picker",
"t-picker-item": "tdesign-miniprogram/picker-item/picker-item",
"t-loading": "tdesign-miniprogram/loading/loading",
"t-select-picker": "../../usercenter/components/ui-select-picker/index"
}
}

View File

@@ -0,0 +1,112 @@
<view class="person-info">
<!-- 页面标题 -->
<view class="page-header">
<view class="header-title">个人信息</view>
<view class="header-subtitle">完善您的个人资料</view>
</view>
<!-- 信息设置卡片 -->
<view class="info-card">
<t-cell-group>
<!-- 微信头像设置 -->
<t-cell
title="微信头像"
center="{{true}}"
t-class-left="order-group__left"
>
<view slot="note" class="avatar-container">
<button
class="avatar-button"
open-type="chooseAvatar"
bind:chooseavatar="onChooseAvatar"
>
<t-avatar
image="{{personInfo.avatarUrl || defaultAvatarUrl}}"
class="avatar-display"
mode="aspectFill"
/>
<view class="avatar-mask">
<text class="avatar-text">点击更换微信头像</text>
</view>
</button>
</view>
</t-cell>
<!-- 微信昵称设置 -->
<t-cell title="微信昵称" t-class="t-cell-class">
<view slot="note" class="nickname-container">
<input
class="nickname-input"
type="nickname"
placeholder="请输入微信昵称"
value="{{personInfo.nickName}}"
bind:input="onNicknameChange"
bind:blur="saveNickname"
bind:confirm="saveNickname"
maxlength="20"
/>
</view>
</t-cell>
<!-- 性别设置 -->
<t-cell
title="性别"
t-class="t-cell-class"
t-class-left="order-group__left"
>
<view slot="note" class="gender-radio-container">
<radio-group bind:change="onGenderChange">
<label class="gender-radio-item">
<radio value="1" checked="{{personInfo.gender == 1}}" color="#667eea"/>
<text class="gender-text">男</text>
</label>
<label class="gender-radio-item">
<radio value="2" checked="{{personInfo.gender == 2}}" color="#667eea"/>
<text class="gender-text">女</text>
</label>
</radio-group>
</view>
</t-cell>
<!-- 手机号设置 -->
<t-cell
bordered="{{false}}"
title="手机号"
t-class="t-cell-class"
t-class-left="order-group__left"
>
<view slot="note" class="phone-input-container">
<input
class="phone-input"
type="number"
placeholder="请输入手机号"
value="{{displayPhoneNumber}}"
bind:input="onPhoneInput"
bind:blur="onPhoneBlur"
bind:confirm="onPhoneConfirm"
bind:focus="onPhoneFocus"
maxlength="11"
/>
</view>
</t-cell>
</t-cell-group>
</view>
<!-- 保存状态提示 -->
<view class="saving-status" wx:if="{{saving}}">
<t-loading theme="circular" size="40rpx" />
<text class="saving-text">正在保存...</text>
</view>
</view>
<!-- 切换账号按钮 -->
<view class="person-info__wrapper">
<view class="person-info__btn" bind:tap="openUnbindConfirm"> 切换账号登录 </view>
</view>
<!-- Toast 提示 -->
<t-toast id="t-toast" />

View File

@@ -0,0 +1,376 @@
:host {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
page {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
}
page view {
box-sizing: border-box;
}
/* 个人信息页面样式 */
.person-info {
padding: 0;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
position: relative;
}
/* 页面标题样式 */
.page-header {
text-align: center;
padding: 80rpx 0 50rpx;
animation: fadeIn 0.8s ease-out;
}
.header-title {
font-size: 52rpx;
font-weight: 700;
color: #fff;
margin-bottom: 20rpx;
text-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.25);
letter-spacing: 2rpx;
}
.header-subtitle {
font-size: 30rpx;
color: rgba(255, 255, 255, 0.85);
font-weight: 400;
letter-spacing: 1rpx;
}
/* 信息卡片样式 */
.info-card {
background: #fff;
border-radius: 28rpx;
margin: 32rpx 24rpx;
box-shadow: 0 12rpx 40rpx rgba(102, 126, 234, 0.15);
overflow: hidden;
animation: slideUp 0.6s ease-out;
padding: 40rpx 32rpx 50rpx;
border: 1rpx solid rgba(102, 126, 234, 0.08);
}
/* 通用按钮样式 */
.person-info__btn {
width: 100%;
height: 96rpx;
background: rgba(255, 255, 255, 0.15);
border: 2rpx solid rgba(255, 255, 255, 0.3);
border-radius: 48rpx;
display: flex;
align-items: center;
justify-content: center;
font-size: 32rpx;
color: #ffffff;
font-weight: 600;
margin-top: 32rpx;
box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
backdrop-filter: blur(10rpx);
transition: all 0.3s ease;
}
.person-info__btn:active {
transform: translateY(2rpx);
box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
background: rgba(255, 255, 255, 0.25);
}
.person-info__wrapper {
padding: 0 32rpx 60rpx;
}
/* 头像相关样式 */
.avatar-container {
position: relative;
width: 120rpx;
height: 120rpx;
display: flex;
align-items: center;
justify-content: center;
}
.avatar-button {
position: relative;
width: 120rpx;
height: 120rpx;
border-radius: 50%;
overflow: hidden;
border: 3rpx solid #667eea;
background: transparent;
padding: 0;
box-shadow: 0 6rpx 20rpx rgba(102, 126, 234, 0.25);
transition: all 0.3s ease;
display: flex;
align-items: center;
justify-content: center;
}
.avatar-button::after {
border: none;
}
.avatar-button:active {
transform: scale(0.96);
box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.35);
}
.avatarUrl {
width: 114rpx;
height: 114rpx;
border-radius: 50%;
object-fit: cover;
}
/* t-avatar 组件样式 */
.avatar-display {
width: 114rpx !important;
height: 114rpx !important;
border-radius: 50% !important;
overflow: hidden !important;
object-fit: cover !important;
}
.avatar-mask {
position: absolute;
top: 3rpx;
left: 3rpx;
width: calc(100% - 6rpx);
height: calc(100% - 6rpx);
background: linear-gradient(135deg, rgba(102, 126, 234, 0.85), rgba(118, 75, 162, 0.85));
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
transition: all 0.3s ease;
backdrop-filter: blur(6rpx);
}
.avatar-button:active .avatar-mask {
opacity: 1;
}
.avatar-text {
color: #fff;
font-size: 20rpx;
text-align: center;
line-height: 1.3;
font-weight: 500;
font-weight: 600;
text-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.3);
}
/* 昵称输入框样式 */
.nickname-container {
display: flex;
flex-direction: column;
align-items: flex-end;
min-width: 300rpx;
}
.nickname-input {
width: 100%;
height: 76rpx;
padding: 0 20rpx;
border: 2rpx solid #e8eaed;
border-radius: 20rpx;
font-size: 28rpx;
color: #333;
background: #f8f9fa;
text-align: right;
box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.nickname-input:focus {
border-color: #667eea;
background: #fff;
box-shadow: 0 6rpx 20rpx rgba(102, 126, 234, 0.18);
transform: translateY(-1rpx);
outline: none;
}
.nickname-input::placeholder {
color: #aaa;
font-size: 26rpx;
}
/* 性别单选框样式 */
.gender-radio-container {
display: flex;
gap: 40rpx;
align-items: center;
}
.gender-radio-container radio-group {
display: flex;
flex-direction: row;
gap: 40rpx;
align-items: center;
}
.gender-radio-item {
display: flex;
align-items: center;
gap: 12rpx;
padding: 8rpx 0;
cursor: pointer;
}
.gender-text {
font-size: 28rpx;
color: #333;
font-weight: 500;
}
/* 手机号输入框样式 */
.phone-input-container {
width: 100%;
display: flex;
justify-content: flex-end;
}
.phone-input {
width: 100%;
height: 76rpx;
padding: 0 20rpx;
border: 2rpx solid #e8eaed;
border-radius: 20rpx;
font-size: 28rpx;
color: #333;
background: #f8f9fa;
text-align: right;
box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.phone-input:focus {
border-color: #667eea;
background: #fff;
box-shadow: 0 6rpx 20rpx rgba(102, 126, 234, 0.18);
transform: translateY(-1rpx);
outline: none;
}
.phone-input::placeholder {
color: #aaa;
font-size: 26rpx;
}
/* 保存状态提示样式 */
.saving-status {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: linear-gradient(135deg, rgba(102, 126, 234, 0.96), rgba(118, 75, 162, 0.96));
color: #fff;
padding: 28rpx 56rpx;
border-radius: 60rpx;
font-size: 30rpx;
z-index: 1000;
backdrop-filter: blur(12rpx);
box-shadow: 0 12rpx 40rpx rgba(102, 126, 234, 0.35);
border: 1rpx solid rgba(255, 255, 255, 0.25);
animation: pulse 1.5s ease-in-out infinite;
}
.saving-text {
font-weight: 600;
letter-spacing: 1rpx;
}
/* Cell组件样式优化 */
.person-info .t-cell-class {
height: 120rpx;
background: transparent;
border-bottom: 1rpx solid rgba(0, 0, 0, 0.05);
}
.person-info .t-cell-class:last-child {
border-bottom: none;
}
/* 添加微妙的动画效果 */
.info-card {
animation: slideUp 0.6s ease-out;
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(80rpx);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.page-header {
animation: fadeIn 0.8s ease-out;
}
@keyframes fadeIn {
from {
opacity: 0;
transform: scale(0.95);
}
to {
opacity: 1;
transform: scale(1);
}
}
@keyframes pulse {
0%, 100% {
transform: scale(1);
}
50% {
transform: scale(1.05);
}
}
/* 响应式设计 */
@media (max-width: 375px) {
.page-header {
padding: 50rpx 24rpx 30rpx;
}
.header-title {
font-size: 42rpx;
}
.header-subtitle {
font-size: 26rpx;
}
.info-card {
margin: 0 24rpx 24rpx;
}
.nickname-container {
min-width: 250rpx;
}
.avatar-container {
width: 120rpx;
height: 120rpx;
}
.avatar-button,
.avatar-display {
width: 120rpx !important;
height: 120rpx !important;
}
.person-info__wrapper {
padding: 0 24rpx 50rpx;
}
}

View File

@@ -0,0 +1,182 @@
// pages/user/phone-verify/index.js
const weChatAuthService = require('../../../services/auth/wechat');
Page({
data: {
phoneNumber: '',
verifyCode: '',
canSendCode: false,
canConfirm: false,
sendCodeText: '发送验证码',
countdown: 0,
loading: false
},
onLoad(options) {
// weChatAuthService 已经是一个实例,直接使用
this.countdownTimer = null;
},
onUnload() {
if (this.countdownTimer) {
clearInterval(this.countdownTimer);
}
},
// 手机号输入
onPhoneInput(e) {
const phoneNumber = e.detail.value;
this.setData({
phoneNumber
});
this.checkCanSendCode();
this.checkCanConfirm();
},
// 验证码输入
onVerifyCodeInput(e) {
const verifyCode = e.detail.value;
this.setData({
verifyCode
});
this.checkCanConfirm();
},
// 检查是否可以发送验证码
checkCanSendCode() {
const { phoneNumber, countdown } = this.data;
const phoneRegex = /^1[3-9]\d{9}$/;
const canSendCode = phoneRegex.test(phoneNumber) && countdown === 0;
this.setData({
canSendCode
});
},
// 检查是否可以确认绑定
checkCanConfirm() {
const { phoneNumber } = this.data;
const phoneRegex = /^1[3-9]\d{9}$/;
const canConfirm = phoneRegex.test(phoneNumber);
this.setData({
canConfirm
});
},
// 发送验证码
async sendVerifyCode() {
if (!this.data.canSendCode) return;
try {
this.setData({ loading: true });
// 这里应该调用后端API发送验证码
// 暂时模拟发送成功
await this.simulateSendCode();
wx.showToast({
title: '验证码已发送',
icon: 'success'
});
// 开始倒计时
this.startCountdown();
} catch (error) {
console.error('发送验证码失败:', error);
wx.showToast({
title: '发送失败,请重试',
icon: 'none'
});
} finally {
this.setData({ loading: false });
}
},
// 模拟发送验证码实际项目中应该调用真实API
simulateSendCode() {
return new Promise((resolve) => {
setTimeout(resolve, 1000);
});
},
// 开始倒计时
startCountdown() {
let countdown = 60;
this.setData({
countdown,
sendCodeText: `${countdown}s后重发`,
canSendCode: false
});
this.countdownTimer = setInterval(() => {
countdown--;
if (countdown > 0) {
this.setData({
countdown,
sendCodeText: `${countdown}s后重发`
});
} else {
this.setData({
countdown: 0,
sendCodeText: '重新发送'
});
this.checkCanSendCode();
clearInterval(this.countdownTimer);
}
}, 1000);
},
// 确认绑定
async confirmBind() {
if (!this.data.canConfirm) return;
try {
this.setData({ loading: true });
const { phoneNumber } = this.data;
// 直接更新用户信息,不验证验证码
await this.updateUserPhone(phoneNumber);
wx.showToast({
title: '绑定成功',
icon: 'success'
});
// 延迟返回上一页
setTimeout(() => {
wx.navigateBack();
}, 1500);
} catch (error) {
console.error('绑定手机号失败:', error);
wx.showToast({
title: error.message || '绑定失败,请重试',
icon: 'none'
});
} finally {
this.setData({ loading: false });
}
},
// 更新用户手机号
async updateUserPhone(phoneNumber) {
try {
// 调用微信授权服务更新用户信息
await weChatAuthService.updateUserProfile({
phoneNumber: phoneNumber
});
// 更新本地存储的用户信息
const userInfo = wx.getStorageSync('userInfo') || {};
userInfo.phoneNumber = phoneNumber;
wx.setStorageSync('userInfo', userInfo);
} catch (error) {
console.error('更新用户手机号失败:', error);
throw error;
}
}
});

View File

@@ -0,0 +1,9 @@
{
"navigationBarTitleText": "绑定手机号",
"navigationBarBackgroundColor": "#ffffff",
"navigationBarTextStyle": "black",
"backgroundColor": "#f5f5f5",
"usingComponents": {
"t-loading": "tdesign-miniprogram/loading/loading"
}
}

View File

@@ -0,0 +1,65 @@
<!--pages/user/phone-verify/index.wxml-->
<view class="phone-verify">
<view class="header">
<view class="title">绑定手机号</view>
<view class="subtitle">绑定手机号后,可以更好地保护您的账户安全</view>
</view>
<view class="form-container">
<!-- 手机号输入 -->
<view class="input-group">
<view class="input-label">手机号</view>
<input
class="phone-input"
type="number"
placeholder="请输入手机号"
value="{{phoneNumber}}"
bindinput="onPhoneInput"
maxlength="11"
/>
</view>
<!-- 验证码输入 -->
<view class="input-group">
<view class="input-label">验证码</view>
<view class="verify-code-container">
<input
class="verify-input"
type="number"
placeholder="请输入验证码"
value="{{verifyCode}}"
bindinput="onVerifyCodeInput"
maxlength="6"
/>
<button
class="send-code-btn {{canSendCode ? '' : 'disabled'}}"
bindtap="sendVerifyCode"
disabled="{{!canSendCode}}"
>
{{sendCodeText}}
</button>
</view>
</view>
</view>
<!-- 操作按钮 -->
<view class="button-container">
<button
class="confirm-btn {{canConfirm ? 'active' : ''}}"
bindtap="confirmBind"
disabled="{{!canConfirm}}"
>
确认绑定
</button>
</view>
<!-- 提示信息 -->
<view class="tips">
<view class="tip-item">• 验证码将发送至您的手机</view>
<view class="tip-item">• 请确保手机号码正确无误</view>
<view class="tip-item">• 如有问题,请联系客服</view>
</view>
</view>
<!-- 加载提示 -->
<t-loading wx:if="{{loading}}" theme="circular" size="40rpx" text="处理中..." />

View File

@@ -0,0 +1,196 @@
/* pages/user/phone-verify/index.wxss */
.phone-verify {
min-height: 100vh;
background-color: #f5f5f5;
padding: 40rpx 32rpx;
}
/* 头部区域 */
.header {
text-align: center;
margin-bottom: 80rpx;
}
.title {
font-size: 48rpx;
font-weight: 600;
color: #333;
margin-bottom: 16rpx;
}
.subtitle {
font-size: 28rpx;
color: #666;
line-height: 1.5;
}
/* 表单容器 */
.form-container {
background: #fff;
border-radius: 16rpx;
padding: 40rpx 32rpx;
margin-bottom: 40rpx;
box-shadow: 0 2rpx 16rpx rgba(0, 0, 0, 0.08);
}
/* 输入组 */
.input-group {
margin-bottom: 40rpx;
}
.input-group:last-child {
margin-bottom: 0;
}
.input-label {
font-size: 28rpx;
color: #333;
margin-bottom: 16rpx;
font-weight: 500;
}
/* 手机号输入框 */
.phone-input {
width: 100%;
height: 88rpx;
padding: 0 24rpx;
border: 2rpx solid #e0e0e0;
border-radius: 12rpx;
font-size: 32rpx;
color: #333;
background: #fff;
transition: border-color 0.3s ease;
}
.phone-input:focus {
border-color: #0052d9;
}
/* 验证码容器 */
.verify-code-container {
display: flex;
align-items: center;
gap: 16rpx;
}
.verify-input {
flex: 1;
height: 88rpx;
padding: 0 24rpx;
border: 2rpx solid #e0e0e0;
border-radius: 12rpx;
font-size: 32rpx;
color: #333;
background: #fff;
transition: border-color 0.3s ease;
}
.verify-input:focus {
border-color: #0052d9;
}
/* 发送验证码按钮 */
.send-code-btn {
width: 200rpx;
height: 88rpx;
background: #0052d9;
color: #fff;
border: none;
border-radius: 12rpx;
font-size: 28rpx;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.3s ease;
}
.send-code-btn.disabled {
background: #ccc;
color: #999;
}
.send-code-btn::after {
border: none;
}
/* 按钮容器 */
.button-container {
margin-bottom: 40rpx;
}
/* 确认按钮 */
.confirm-btn {
width: 100%;
height: 96rpx;
background: #ccc;
color: #999;
border: none;
border-radius: 12rpx;
font-size: 32rpx;
font-weight: 500;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.3s ease;
}
.confirm-btn.active {
background: #0052d9;
color: #fff;
}
.confirm-btn::after {
border: none;
}
/* 提示信息 */
.tips {
background: #fff;
border-radius: 16rpx;
padding: 32rpx;
box-shadow: 0 2rpx 16rpx rgba(0, 0, 0, 0.08);
}
.tip-item {
font-size: 26rpx;
color: #666;
line-height: 1.6;
margin-bottom: 12rpx;
}
.tip-item:last-child {
margin-bottom: 0;
}
/* 加载状态 */
.t-loading {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 9999;
}
/* 响应式设计 */
@media (max-width: 375px) {
.phone-verify {
padding: 32rpx 24rpx;
}
.title {
font-size: 44rpx;
}
.subtitle {
font-size: 26rpx;
}
.form-container {
padding: 32rpx 24rpx;
}
.send-code-btn {
width: 180rpx;
font-size: 26rpx;
}
}